@ComponentScan
@EnableAutoConfiguration
@PropertySource(value = { "file:/Users/Documents/workspace/application.properties" })
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
}
在本例中,它在部署时给出:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] found for dependency:
无法找到外部化应用程序属性文件的正确方法
我尝试自动装配正确加载的环境变量,但随后我需要手动定义所有bean
@Bean
public JdbcTemplate dataSource() {
String driverClassName = env
.getProperty("spring.datasource.driverClassName");
String dsUrl = env.getProperty("spring.datasource.url");
String username = env.getProperty("spring.datasource.username");
String password = env.getProperty("spring.datasource.password");
//DataSource dataSource = new SimpleDriverDataSource(new driverClassName, dsUrl, username, password);
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
return jdbc;
}
此部署没有抛出错误,但没有响应。
如果要将WAR部署到Tomcat,则需要定义上下文XML,如下所示:https://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Defining_a_context
例如,如果您有http://localhost:8080/my-app/.
,则通常会定义$CATALINA_BASE/conf/Catalina/localhost/my-app.xml。文件看起来像这样:
<Context docBase='path/to/my-app/my-app.war'>
<Environment name='app_config_dir' value='path/to/my-app/' type='java.lang.String'/>
</Context>
在你的代码中,实现ApplicationContextAware并重写setApplicationContext。下面是一个例子:
public class Setup implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
log.info("Set application context. App Config Property: {}",applicationContext.getEnvironment().getProperty("app_config_dir"));
}
}
现在可以从app_config_dir
加载属性文件
不需要使用@PropertySource
注释来定义它。您应该使用spring.config.location
属性来设置您的application.properties
位置。该属性可以在命令行中设置,例如:
java -jar myapp.jar --spring.config.location=/Users/Documents/workspace/
您可以定义一个名为SPRING_CONFIG_LOCATION
的环境变量,并为其指定一个值,该值可以是一个文件夹(以/
结尾)或一个文件。在任何情况下,位置都应该加上file:
:
SPRING_CONFIG_LOCATION = file:C:/workspace/application.properties
或
SPRING_CONFIG_LOCATION = file:C:/workspace/
您也可以使用@PropertySource
,因为当您将应用程序作为war文件部署到tomcat时,它很有用。
@PropertySource
不工作,因为您缺少@Configuration
注释。根据Spring-Boot文档,@PropertySource
注释应该出现在@Configuration
类上。
@Configuration
@ComponentScan
@EnableAutoConfiguration
@PropertySource(value = { "file:/Users/Documents/workspace/application.properties" })
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
}
您也可以加载多个属性文件。例:
@PropertySource(value = {"classpath:application.properties", "file:/Users/overriding.propertis"}, ignoreResourceNotFound = true)
注意声明文件的顺序很重要。如果在两个或多个文件中定义了相同的键,则在最后声明的文件中与该键关联的值将覆盖之前的任何值。