如何自动连接弹簧环境对象
2022-09-03 12:55:35
我正在尝试从应用程序对象内的 .properties 文件中获取属性。我唯一知道如何做到这一点的知识是通过对象。Environment
它在我的配置中效果很好...
@Configuration
@ComponentScan(basePackages = {
"com.production"
})
@PropertySource(value = {
"classpath:/application.properties",
"classpath:/environment-${FETTER_ENVIRONMENT}.properties"
})
@EnableJpaRepositories("com.production.repositories")
@EnableTransactionManagement
public class Config {
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USER = "db.user";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
@Resource
Environment environment;
但是我尝试在另一个类中执行此操作,但它为空。我尝试过使用和手动注射。@Resource
@Autowired
有什么特别之处可以防止这种情况吗?Environment
@Component
public class Vendor {
private String token;
@Autowired
private Environment environment;
public Vendor() {
//get token from config
//Environment environment = (Environment) ApplicationContextProvider.getApplicationContext().getBean("environment");
setToken(environment.getProperty("api.vendor.token"));
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
更新:我发现这个资源突出显示了 的用法,但我在我的应用程序中不使用任何 XML 配置。@Value
看起来这可能就是我正在寻找的:以编程方式在Spring 3.1中加载属性