- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
同事们,这似乎是一个愚蠢的问题,但我无法从属性文件中读取属性。
我有一个 Spring 配置类:
@EnableWs
@Configuration
@PropertySource("classpath:appl.properties")
public class WebServiceConfig extends WsConfigurerAdapter {
/*Some beans*/
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
@Value("${db_name.db.url}")
private String DBUrl;
@Bean
@ConfigurationProperties(prefix="datasource.secondary")
public BasicDataSource DBDataSource() {
System.out.println("DBUrl: " + DBUrl);
BasicDataSource DBDataSource = new BasicDataSource();
DWDataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
DWDataSource.setUrl(DBUrl);
DWDataSource.setUsername("user");
DWDataSource.setPassword("pass");
DWDataSource.setMaxIdle(10);
DWDataSource.setMaxWaitMillis(10000);
DWDataSource.setValidationQuery("select 1");
DWDataSource.setTestOnBorrow(false);
DWDataSource.setTestWhileIdle(true);
DWDataSource.setDefaultAutoCommit(true);
return DBDataSource;
}
}
属性文件如下所示:
#bla bla bla
#bla bla bla
#bla bla bla
db_name.db.url=jdbc:sqlserver://bla
db_name.db.user=user
db_name.db.password=pass
当我运行程序并尝试调用数据库时,我收到下一个堆栈跟踪:
INFO : [oct-27 10:48:48,834] service.app.WsEndpoint - Error retrieving database metadata; nested exception is org.springframework.jdbc.support.Me taDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionExc eption: Could not get JDBC Connection; nested exception is java.sql.SQLException: Cannot create JDBC driver of class 'com.microsoft.sqlserver.jdb c.SQLServerDriver' for connect URL 'null'
没有其他异常(exception)。
但是在属性文件中我有 db_name.db.url=db_name.db.url=jdbc:sqlserver://bla
为什么为空?
如果我改变了
@Value("${db_name.db.url}")
private String DBWUrl;
到
@Value("${db_name.db.url}")
private String DBUrl = "jdbc:sqlserver://bla";
在 Spring 配置 Java 类中我工作正常。
更新
Spring启动日志:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.2.5.RELEASE)
INFO : [oct-27 11:37:53,555] service.app.WsApplication - Starting WsApplication on MyPC with PID 6688 (C:\Users\Maya\workspace\WS\ta
rget\classes started by Maya in C:\Users\Maya\workspace\WS)
INFO : [oct-27 11:37:53,635] context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Refreshing org.springframework.boot.context.embedde
d.AnnotationConfigEmbeddedWebApplicationContext@10bbd20a: startup date [Tue Oct 27 11:37:53 MSK 2015]; root of context hierarchy
INFO : [oct-27 11:37:54,868] factory.support.DefaultListableBeanFactory - Overriding bean definition for bean 'beanNameViewResolver': replacing [
Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factor
yBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewRe
solver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAut
oConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; de
pendencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvc
AutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resour
ce [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
INFO : [oct-27 11:37:55,511] internal.util.Version - HV000001: Hibernate Validator 5.1.3.Final
INFO : [oct-27 11:37:55,693] context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'webServiceConfig' of type [class
com.mayacomp.service.app.WebServiceConfig$$EnhancerBySpringCGLIB$$9406d7b6] is not eligible for getting processed by all BeanPostProcessors
(for example: not eligible for auto-proxying)
INFO : [oct-27 11:37:55,713] context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.ws.config.ann
otation.DelegatingWsConfiguration' of type [class org.springframework.ws.config.annotation.DelegatingWsConfiguration$$EnhancerBySpringCGLIB$$f512
4549] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
INFO : [oct-27 11:37:55,785] addressing.server.AnnotationActionEndpointMapping - Supporting [WS-Addressing August 2004, WS-Addressing 1.0]
INFO : [oct-27 11:37:55,864] context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.a
nnotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfigurat
ion$$EnhancerBySpringCGLIB$$723342a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying
)
INFO : [oct-27 11:37:55,888] context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'transactionAttributeSource' of ty
pe [class org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] is not eligible for getting processed by all BeanPostP
rocessors (for example: not eligible for auto-proxying)
INFO : [oct-27 11:37:55,903] context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'transactionInterceptor' of type [
class org.springframework.transaction.interceptor.TransactionInterceptor] is not eligible for getting processed by all BeanPostProcessors (for ex
ample: not eligible for auto-proxying)
INFO : [oct-27 11:37:55,909] context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.c
onfig.internalTransactionAdvisor' of type [class org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor] is not
eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
INFO : [oct-27 11:37:56,557] embedded.tomcat.TomcatEmbeddedServletContainer - Tomcat initialized with port(s): 8080 (http)
INFO : [oct-27 11:37:56,933] catalina.core.StandardService - Starting service Tomcat
INFO : [oct-27 11:37:56,935] catalina.core.StandardEngine - Starting Servlet Engine: Apache Tomcat/8.0.23
INFO : [oct-27 11:37:57,077] [Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
INFO : [oct-27 11:37:57,078] web.context.ContextLoader - Root WebApplicationContext: initialization completed in 3447 ms
INFO : [oct-27 11:37:57,902] context.embedded.ServletRegistrationBean - Mapping servlet: 'messageDispatcherServlet' to [/services/*]
INFO : [oct-27 11:37:57,904] context.embedded.ServletRegistrationBean - Mapping servlet: 'dispatcherServlet' to [/]
INFO : [oct-27 11:37:57,912] context.embedded.FilterRegistrationBean - Mapping filter: 'characterEncodingFilter' to: [/*]
INFO : [oct-27 11:37:57,913] context.embedded.FilterRegistrationBean - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
DBUrl: jdbc:sqlserver://bla
INFO : [oct-27 11:37:59,160] method.annotation.RequestMappingHandlerMapping - Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produ
ces=[],custom=[]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boo
t.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
INFO : [oct-27 11:37:59,161] method.annotation.RequestMappingHandlerMapping - Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produ
ces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorControl
ler.errorHtml(javax.servlet.http.HttpServletRequest)
INFO : [oct-27 11:37:59,189] servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/webjars/**] onto handler of type [class org.springframew
ork.web.servlet.resource.ResourceHttpRequestHandler]
INFO : [oct-27 11:37:59,189] servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/**] onto handler of type [class org.springframework.web.
servlet.resource.ResourceHttpRequestHandler]
INFO : [oct-27 11:37:59,234] servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/**/favicon.ico] onto handler of type [class org.springfr
amework.web.servlet.resource.ResourceHttpRequestHandler]
INFO : [oct-27 11:37:59,399] export.annotation.AnnotationMBeanExporter - Registering beans for JMX exposure on startup
INFO : [oct-27 11:37:59,402] export.annotation.AnnotationMBeanExporter - Bean with name 'WorkDBDataSource' has been autodetected for JMX exposure
INFO : [oct-27 11:37:59,402] export.annotation.AnnotationMBeanExporter - Bean with name 'DWDataSource' has been autodetected for JMX exposure
INFO : [oct-27 11:37:59,408] export.annotation.AnnotationMBeanExporter - Located MBean 'WorkDBDataSource': registering with JMX server as MBean [
org.apache.commons.dbcp2:name=WorkDBDataSource,type=BasicDataSource]
INFO : [oct-27 11:37:59,411] export.annotation.AnnotationMBeanExporter - Located MBean 'DWDataSource': registering with JMX server as MBean [org.
apache.commons.dbcp2:name=DWDataSource,type=BasicDataSource]
INFO : [oct-27 11:37:59,446] coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-8080"]
INFO : [oct-27 11:37:59,455] coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8080"]
INFO : [oct-27 11:37:59,478] util.net.NioSelectorPool - Using a shared selector for servlet write/read
INFO : [oct-27 11:37:59,505] embedded.tomcat.TomcatEmbeddedServletContainer - Tomcat started on port(s): 8080 (http)
INFO : [oct-27 11:37:59,509] service.app.WsApplication - Started WsApplication in 6.421 seconds (JVM running for 7.159)
最佳答案
您可以使用环境变量来获取 application.properties 中的属性,例如
@Autowired
Environment env;
@Bean
@ConfigurationProperties(prefix="datasource.secondary")
public BasicDataSource DBDataSource() {
// Notice this line
System.out.println("DBUrl: " + env.getProperty("db_name.db.url"));
BasicDataSource DBDataSource = new BasicDataSource();
DWDataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
DWDataSource.setUrl(DBUrl);
DWDataSource.setUsername("user");
DWDataSource.setPassword("pass");
DWDataSource.setMaxIdle(10);
DWDataSource.setMaxWaitMillis(10000);
DWDataSource.setValidationQuery("select 1");
DWDataSource.setTestOnBorrow(false);
DWDataSource.setTestWhileIdle(true);
DWDataSource.setDefaultAutoCommit(true);
return DBDataSource;
}
注意:application.properties 文件必须放在类路径(src/main/resources)中。
关于java - 为什么注解@Value在使用Spring PropertySourcesPlaceholderConfigurer时总是返回null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33362763/
由于我们相当复杂的 properties 文件设置,我们不能简单地使用 @PropertySource。 这是属性文件: connection.http.connectTimeout=15000 #c
我有一个包含值的属性文件,如 jdbc.password={enc}laksksjdjdj 使用 JDK 1.7 和 Spring 4.1.5 我的配置类如下所示 @PropertySources({
PropertySourcesPlaceholderConfigurer 适用于我的 @Value,但不用于以下广告数据源配置 @Bean @ConfigurationProperties(prefi
我对遗留代码(它是 Spring 应用程序)进行了分析,发现 PropertySourcesPlaceholderConfigurer 和 PropertyPlaceholderConfigurer
我正在将一个工作项目从使用 SpringBoot 命令行参数转移到从文件中读取属性。以下是@Configuration类所涉及的部分: @Configuration class RemoteCommu
我使用DES算法对jdbc.properties中的用户名和密码进行加密,并使用PropertyPlaceholderConfigurer进行解密,但发现该类已被弃用。所以使用PropertySour
我想在 spring context xml 中定义一个自定义的 PropertySourcesPlaceholderConfigurer。我想在那里使用多个 PropertySources,以便我可
PropertySourcesPlaceHolderConfigurer 可以从属性源查找占位符的值。是否有与 PropertyOverrideConfigurer 等效的方法,它使用属性源来覆盖属性
我试图了解不使用@Autowiring 和Spring Environment 类时@PropertySource 注释的行为。我正在尝试使用 @Value 在运行时从属性文件中注入(inject)值
我的应用程序中有两个模块: 核心 网络 core 模块在 spring/applicationContext-core.xml 上下文中包含以下属性占位符配置:
我有一个关于 PropertySourcesPlaceholderConfigurer 和 @PropertySource 注释的简单问题。我有简单的 bean 类类(class)。我想从 appli
我有一个使用 PropertySourcesPlaceholderConfigurer 加载设置的 spring 3.1 应用程序,我想管理测试和生产环境,只需从服务器上下文加载设置,覆盖本地文件属性
我正在开发一个 Spring 应用程序,我意识到我在管理我的属性的方式上存在问题。 我使用 Spring 环境配置文件来加载我的属性,并且我最近添加了更多配置文件,这使我的属性文件无法管理。 属性文件
查看 3.1 (http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-property-management/) 中新的 spri
如何使用自定义 .properties 文件为不同的环境(生产、开发、暂存)配置 PropertySourcesPlaceholderConfigurer?在部署 spring 时抛出“无法解析字符串
我一直在尝试获取在 Spring 应用程序中运行的自定义 PropertySource 的非常基本的示例。 这是我的 PropertySource: public class RemoteProper
我有以下配置类: @Configuration @PropertySource(name = "props", value = "classpath:/app-config.properties")
我正在尝试使用 PropertySourcesPlaceholderConfigurer。但是,我对“本地属性”和“环境属性”的概念感到困惑,如 Spring API javadoc 中所示: Sea
我希望 Spring 首先检查 JBoss EAP 6.2(使用 JBoss AS 7.2)中的系统属性,然后检查位于 jar 内的属性。 我试过了 但这使用 jar 中的属性而不是 JBoss 的
我是一名优秀的程序员,十分优秀!