Spring 自动装配自动装配 bean 中的属性

ans*_*set 5 java spring spring-boot

我是 Spring 的新手。我遇到了 Spring Boot 的问题。我正在尝试将外部配置文件中的字段自动装配到自动装配的 bean 中。我有以下课程

应用程序.java

public class App {

@Autowired
private Service service;

public static void main(String[] args) {

    final SpringApplication app = new SpringApplication(App.class);
    //app.setShowBanner(false);
    app.run();
}

@PostConstruct
public void foo() {
    System.out.println("Instantiated service name = " + service.serviceName);
}
}
Run Code Online (Sandbox Code Playgroud)

应用程序配置.java

@Configuration
@ConfigurationProperties
public class AppConfig {

@Bean
public Service service()    {
    return new Service1();
}
}
Run Code Online (Sandbox Code Playgroud)

服务接口

public interface Service {
    public String serviceName ="";
    public void getHistory(int days , Location location );
    public void getForecast(int days , Location location );
}
Run Code Online (Sandbox Code Playgroud)

服务1

@Configurable
@ConfigurationProperties
public class Service1 implements Service {

@Autowired
@Value("${serviceName}") 
public String serviceName;
//Available in external configuration file.
//This autowiring is not reflected in the main method of the application.



public void getHistory(int days , Location location)
{
    //history code
}

public void getForecast(int days , Location location )
{
    //forecast code
}
}
Run Code Online (Sandbox Code Playgroud)

我无法在 App 类的 postconstruct 方法中显示服务名称变量。我这样做对吗?

Edd*_*dez 5

您可以通过不同的方式加载属性:

想象一下下面的 application.properties 由 spring-boot 自动加载。

spring.app.serviceName=Boot demo
spring.app.version=1.0.0
Run Code Online (Sandbox Code Playgroud)
  1. 使用@Value注入值

    @Service
    public class ServiceImpl implements Service {
    
    @Value("${spring.app.serviceName}") 
    public String serviceName;
    
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用@ConfigurationProperties注入值

    @ConfigurationProperties(prefix="spring.app")
    public class ApplicationProperties {
    
       private String serviceName;
    
       private String version;
    
       //setters and getters
    }
    
    Run Code Online (Sandbox Code Playgroud)

您可以使用另一个类访问此属性@Autowired

@Service
public class ServiceImpl implements Service {

@Autowired
public ApplicationProperties applicationProperties;

}
Run Code Online (Sandbox Code Playgroud)

正如您所注意到的,前缀将是spring.app,然后 spring-boot 将与属性前缀匹配,并查找serviceNameversion并将注入值。