Java – used in spring Properties without using XML configuration

I found one in the article on using java based configuration and x000 in spring Properties file The illustrations are as follows My question is "is there a way to use only Java based configuration to use. Properties files without using XML files?"

Is there any way to omit @ importresource and use Java based pure configuration in the following code?

@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);
   }
}

Performance - config In 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=

Sample main method

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

Solution

Try this

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

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

Or use 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/ Learn more

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>