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();
}
}