【问题标题】:Spring JavaConfig properties in bean is not getting set?bean 中的 Spring JavaConfig 属性未设置?
【发布时间】:2013-03-18 14:06:53
【问题描述】:

我正在考虑将 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 中的值?

【问题讨论】:

  • @Override public void addResourceHandlers(ResourceHandlerRegistry registry) 方法的实现有误。正确的实现是registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");

标签: java spring spring-mvc


【解决方案1】:

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

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

应该是:

@PropertySource("classpath:application.properties")

基于此:

Spring PropertySource Documentation

另外,基于上面的链接,既然您提到您正在转换为 java config 方法而不是 xml,我认为以下可能是您问题的解决方案:

解析 ${...} 中的占位符和 @Value 注释 为了在定义或@Value 中解析 ${...} 占位符 使用 PropertySource 中的属性的注释,必须注册 一个 PropertySourcesPlaceholderConfigurer。这会自动发生 在 XML 中使用时,但必须 使用时使用静态@Bean 方法显式注册 @配置类。请参阅“使用外化值” @Configuration Javadoc 的部分和“关于 @Bean Javadoc 的 BeanFactoryPostProcessor-返回 @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"));

对于剩余的属性值以此类推。我只是不熟悉你这样做的方式。我知道上述方法会奏效。

【讨论】:

  • 我改变了它并没有帮助:(
  • 我认为我刚刚发布的最后一件事可能是您的解决方案。由于您刚刚转换为 java config 而不是 xml 配置。您是否将 PropertySourcesPlaceholderConfigurer 添加到您的配置中?
  • 我想我在属性文件中发现了问题,密码是 rt.setPassword=Waiting#$\ 并且它不允许下一行工作
  • 但我不知道如何使它与 Waiting#$\ 的密码值一起工作
  • 您在答案开头所做的声明不正确。 @PropertySource(value = "classpath:application.properties")@PropertySource("classpath:application.properties") 本质上是完全相同的东西,因为如果没有将属性名称传递到注解声明中,则默认填充注解的 value 属性。
【解决方案2】:

除了@ssn771 答案涉及注入Environment 并通过它检索属性(这确实是建议的做法),this is what I've done as a workaround 无需更改@Value 在@987654324 中的使用方式@POJO。

【讨论】:

    【解决方案3】:

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

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

    来自 PropertySourcesPlaceholderConfigurer 的 javadoc:

    此类被设计为 Spring 3.1 应用程序中 PropertyPlaceholderConfigurer 的一般替代品。它默认用于支持在 spring-context-3.1 XSD 中使用的 property-placeholder 元素,而 spring-context 版本

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多