我是春天的新手.我遇到了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方法中显示服务名称变量.我这样做了吗?
解决方法:
您可以通过不同方式加载属性:
想象一下以下由spring-boot自动加载的application.properties.
spring.app.serviceName=Boot demo
spring.app.version=1.0.0
>使用@Value注入值
@Service
public class ServiceImpl implements Service {
@Value("${spring.app.serviceName}")
public String serviceName;
}
>使用@ConfigurationProperties注入值
@ConfigurationProperties(prefix="spring.app")
public class ApplicationProperties {
private String serviceName;
private String version;
//setters and getters
}
您可以使用@Autowired从另一个类访问此属性
@Service
public class ServiceImpl implements Service {
@Autowired
public ApplicationProperties applicationProperties;
}
您可以注意到前缀是spring.app,然后spring-boot将匹配属性前缀,并查找serviceName,并注入版本和值.
标签:java,spring,spring-boot-2
来源: https://codeday.me/bug/20190609/1204897.html