Use .properties without using xml config in spring

I found a way to use .properties files in spring while using Java and xml configuration from this article. The illustrations are as follows. My question is " Is it possible to use .properties files only using Java based configuration without using xml files? "

ie Is there a way to skip @ImportResource

in the following code and use pure Java based configuration?

@Configuration
@ImportResource("classpath:/com/acme/properties-config.xml")
public class AppConfig {
   private @Value("${jdbc.url}") String url;
   private @Value("${jdbc.username}") String username;
   private @Value("${jdbc.password}") String password;

   public @Bean DataSource dataSource() {
      return new DriverManagerDataSource(url, username, password);
   }
}

      

properties-config.xml

<beans>
   <context:property-placeholder location="classpath:/com/acme/jdbc.properties"/>
</beans>

      

jdbc.properties

jdbc.url=jdbc:hsqldb:hsql://localhost/xdb
jdbc.username=sa
jdbc.password=

      

Basic method example

public static void main(String[] args) {
   ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
   TransferService transferService = ctx.getBean(TransferService.class);
   // ...
}

      

+3


source to share


1 answer


try it

@Configuration
@PropertySource("/app.properties")
public class Test {
    @Value("${prop1}")
    String prop1;

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

      

or using the environment



@Configuration
@PropertySource("/app.properties")
public class Test {
    @Autowired
    Environment env;

    @Bean
    public DataSource dataSource() {
        return new DriverManagerDataSource(env.getProperty("url"), env.getProperty("username"), env.getProperty("password"));
    }
}

      

read this article http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-property-management/ for more information

+7


source







All Articles