springboot 配置文件属性配置

本文详细介绍如何在Spring Boot项目中使用application.properties配置文件自定义变量,并通过@Value和@ConfigurationProperties注解进行属性注入,同时提供了多种注入方式的示例,包括直接注入、通过bean注入及配置类注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 可以在application.properties 配置文件里自定义变量,调用的时候使用 @Value 注解

 2. 以上是直接调用配置文件中的属性,下面我们换一种方式:通过

@ConfigurationProperties注解将属性注入到 bean 中,然后通过
@Component将 bean 注入到 spring 容器中

3. 2的变形

Teacher 类上面不加注解, 在启动类使用 @Bean 注解注入,在 java 文件中调用是一样的

package com.example.firstspringboot;

import com.example.firstspringboot.bean.Teacher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class FirstspringbootApplication {

    private static final Logger logger = LoggerFactory.getLogger(Logger.class);

    public static void main(String[] args) {
        SpringApplication.run(FirstspringbootApplication.class, args);
        logger.info("-----------叮咚成功-------------");
    }

    @Bean
    @ConfigurationProperties(prefix = "teacher")
    public Teacher  teacher(){
        return new Teacher();
    }
}

4. 3的变形

不在启动类里注入,另写一个配置类。启动类最好尽量简洁。

package com.example.firstspringboot.config;

import com.example.firstspringboot.bean.Teacher;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class JavaConfig {

    @Bean
    @ConfigurationProperties(prefix = "teacher")
    public Teacher teacher(){
        return new Teacher();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值