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

时间:2015-05-06 14:54:24

标签: java spring spring-boot

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

App.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);
}
}

AppConfig.java

@Configuration
@ConfigurationProperties
public class AppConfig {

@Bean
public Service service()    {
    return new Service1();
}
}

服务接口

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

服务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
}
}

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

2 个答案:

答案 0 :(得分:3)

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

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

spring.app.serviceName=Boot demo
spring.app.version=1.0.0
  1. 使用@Value

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

    注入值
    @ConfigurationProperties(prefix="spring.app")
    public class ApplicationProperties {
    
       private String serviceName;
    
       private String version;
    
       //setters and getters
    }
    
  3. 您可以使用@Autowired

    从其他类访问此属性
    @Service
    public class ServiceImpl implements Service {
    
    @Autowired
    public ApplicationProperties applicationProperties;
    
    }
    

    您可以注意到前缀为spring.app,然后spring-boot将匹配属性前缀,并查找serviceNameversion,并注入值。

答案 1 :(得分:2)

考虑到您在顶部包中注明了App@SpringBootApplication类,您可以将App放在serviceName内并使用application.properties。如果您已经在配置上使用@Value("${serviceName}")它将会发生冲突,请不要在课程上使用@Component,因此@Bean@Autowired

有关详细信息,请参阅docs

你会以

之类的结尾
@Value

当你有@ Component / @ Service / @ Repository

时,不需要@Bean声明
@Service // @Component specialization
public class Service1 implements Service {

@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
}
}

你的主要班级

@Configuration
public class AppConfig {  //other stuff here not duplicated beans  }
相关问题