David Williams
David Williams

Reputation: 8664

@Value Annotation Syntax Issue

In a Spring MVC anotation driven web app I have this as my container config

@EnableWebMvc
@Configuration
@ComponentScan("com.mobiusinversion.web")
public class Config {

    @Value("${jdbc.driverClassName}")   private String driverClassName;
    @Value("${jdbc.url}")               private String url;
    @Value("${jdbc.username}")          private String username;
    @Value("${jdbc.password}")          private String password;

and in my application.properties, I have

 ################### JDBC Configuration ##########################
 jdbc.driverClassName=org.hsqldb.jdbcDriver
 jdbc.url=jdbc:hsqldb:file:db/myDB;shutdown=true
 jdbc.username=david
 jdbc.password=

But when I deploy my war in the webapps directory of my jetty server, I get this error:

Caused by: 
java.lang.ClassNotFoundException: ${jdbc.driverClassName}
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:436)
    at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:389)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:270)

So clearly this property is not getting processed. How do I use the @Value annotation correctly to configure this property?

Upvotes: 0

Views: 412

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280168

You need to provide a PropertySourcesPlaceholderConfigurer bean in your context. For Java configuration, it has to be provided through a static @Bean method so that Spring has a hint that it is a BeanFactoryPostProcessor and doesn't need (should be initialized before) the @Configuration bean.

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

If you don't provide PropertySources directly through a PropertySourcesPlaceholderConfigurer setter within the @Bean method above, you have to provide the source in another way. For example, with @PropertySource

@EnableWebMvc
@Configuration
@ComponentScan("com.mobiusinversion.web")
@PropertySource("classpath:your.properties")
public class Config {

Upvotes: 2

Related Questions