spring PropertyPlaceholderConfigurer and context:property-placeholder

前端 未结 3 1968
长发绾君心
长发绾君心 2020-11-30 00:35

I have following bean declaration:

  
        

        
3条回答
  •  -上瘾入骨i
    2020-11-30 01:26

    is the XML equivalent to the PropertyPlaceholderConfigurer. So, prefer that. The simply factories a java.util.Properties instance that you can inject.

    In Spring 3.1 (not 3.0...) you can do something like this:

    @Configuration
    @PropertySource("/foo/bar/services.properties")
    public class ServiceConfiguration { 
    
        @Autowired Environment environment; 
    
        @Bean public javax.sql.DataSource dataSource( ){ 
            String user = this.environment.getProperty("ds.user");
            ...
        } 
    }
    

    In Spring 3.0, you can "access" properties defined using the PropertyPlaceHolderConfigurer mechanism using the SpEl annotations:

    @Value("${ds.user}") private String user;
    

    If you want to remove the XML all together, simply register the PropertyPlaceholderConfigurer manually using Java configuration. I prefer the 3.1 approach. But, if youre using the Spring 3.0 approach (since 3.1's not GA yet...), you can now define the above XML like this:

    @Configuration 
    public class MySpring3Configuration {     
            @Bean 
            public static PropertyPlaceholderConfigurer configurer() { 
                 PropertyPlaceholderConfigurer ppc = ...
                 ppc.setLocations(...);
                 return ppc; 
            } 
    
            @Bean 
            public class DataSource dataSource(
                    @Value("${ds.user}") String user, 
                    @Value("${ds.pw}") String pw, 
                    ...) { 
                DataSource ds = ...
                ds.setUser(user);
                ds.setPassword(pw);                        
                ...
                return ds;
            }
    }
    

    Note that the PPC is defined using a static bean definition method. This is required to make sure the bean is registered early, because the PPC is a BeanFactoryPostProcessor - it can influence the registration of the beans themselves in the context, so it necessarily has to be registered before everything else.

提交回复
热议问题