bean中的Spring JavaConfig属性没有设置?

时间:2013-03-18 14:06:54

标签: java spring spring-mvc

我正在考虑将Spring JavaConfig与一些属性文件一起使用,但是bean中的属性没有设置?在bean中没有设置?

这是我的WebConfig:

@Configuration
@EnableWebMvc
@PropertySource(value = "classpath:application.properties")
@Import(DatabaseConfig.class)
@ImportResource("/WEB-INF/applicationContext.xml")
public class WebMVCConfig extends WebMvcConfigurerAdapter {

    private static final String MESSAGE_SOURCE = "/WEB-INF/classes/messages";

    private static final Logger logger = LoggerFactory.getLogger(WebMVCConfig.class);

    @Value("${rt.setPassword}")
    private String RTPassword;

    @Value("${rt.setUrl}")
    private String RTURL;

    @Value("${rt.setUser}")
    private String RTUser;


    @Bean
    public  ViewResolver resolver() {
        UrlBasedViewResolver url = new UrlBasedViewResolver();
        url.setPrefix("/WEB-INF/view/");
        url.setViewClass(JstlView.class);
        url.setSuffix(".jsp");
        return url;
    }


    @Bean(name = "messageSource")
    public MessageSource configureMessageSource() {
        logger.debug("setting up message source");
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename(MESSAGE_SOURCE);
        messageSource.setCacheSeconds(5);
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver lr = new SessionLocaleResolver();
        lr.setDefaultLocale(Locale.ENGLISH);
        return lr;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        logger.debug("setting up resource handlers");
        registry.addResourceHandler("/resources/").addResourceLocations("/resources/**");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        logger.debug("configureDefaultServletHandling");
        configurer.enable();
    }

    @Override
    public void addInterceptors(final InterceptorRegistry registry) {
        registry.addInterceptor(new LocaleChangeInterceptor());
    }

    @Bean
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver();

        Properties mappings = new Properties();
        mappings.put("org.springframework.web.servlet.PageNotFound", "p404");
        mappings.put("org.springframework.dao.DataAccessException", "dataAccessFailure");
        mappings.put("org.springframework.transaction.TransactionException", "dataAccessFailure");
        b.setExceptionMappings(mappings);
        return b;
    }

    @Bean
    public RequestTrackerConfig requestTrackerConfig()
    {
        RequestTrackerConfig tr = new RequestTrackerConfig();
        tr.setPassword(RTPassword);
        tr.setUrl(RTURL);
        tr.setUser(RTUser);

        return tr;
    }


}

tr.url中的值是“rt.setUrl”而不是application.properties中的值?

3 个答案:

答案 0 :(得分:4)

我不是100%,但我认为你的@PropertySource不太正确。而不是

@PropertySource(value = "classpath:application.properties")

应该是:

@PropertySource("classpath:application.properties")

基于此:

Spring PropertySource Documentation

另外,根据上面的链接,因为你提到你转换为java配置方法而不是xml,我认为以下可能是你的问题的解决方案:

  

解决$ {...}占位符和@Value注释   为了解决定义或@Value中的$ {...}占位符   使用PropertySource属性的注释,必须注册   PropertySourcesPlaceholderConfigurer。这会自动发生   在XML中使用时,必须是   使用时使用静态@Bean方法显式注册   @Configuration类。请参阅“使用外部化值”   @Configuration Javadoc的一节和“关于。的注释   BeanFactoryPostProcessor-返回@Bean Javadoc的@Bean方法   细节和例子。

以上链接中的示例是我通常的做法:

 @Configuration
 @PropertySource("classpath:/com/myco/app.properties")
 public class AppConfig {
     @Autowired
     Environment env;

     @Bean
     public TestBean testBean() {
         TestBean testBean = new TestBean();
         testBean.setName(env.getProperty("testbean.name"));
         return testBean;
    }
 }

所以在顶部添加:

@Autowired
Environment env;

然后在你的方法中使用:

tr.setPassword(env.getProperty("rt.setPassword"));

等等剩余的属性值。我对你的做法并不熟悉。我知道上述方法可行。

答案 1 :(得分:0)

除了@ ssn771回答涉及注入Environment并通过它检索属性这确实是建议的方式,this is what I've done as a workaround而不必改变@Value的方式是在@Configuration POJO中使用。

答案 2 :(得分:0)

在许多建议的事情中,最重要的是你需要在Spring 3.1+(或Spring 3.0中的PropertySourcesPlaceholderConfigurer)中配置PropertyPlaceholderConfigurer。如果要将其应用于配置类(使用static注释),则必须为@Value

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

来自PropertySourcesPlaceholderConfigurer的javadoc:

  

此类被设计为Spring 3.1应用程序中PropertyPlaceholderConfigurer的一般替代品。默认情况下,它支持property-placeholder元素处理spring-context-3.1 XSD,而spring-context版本< = 3.0默认为PropertyPlaceholderConfigurer以确保向后兼容性。有关完整的详细信息,请参阅spring-context XSD文档。

相关问题