java bean 中的 Spring JavaConfig 属性未设置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15478806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:44:25  来源:igfitidea点击:

Spring JavaConfig properties in bean is not getting set?

javaspringspring-mvc

提问by SJS

I am looking at using Spring JavaConfig with some property files but properties in bean is not getting set?in bean is not getting set?

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

Here is my WebConfig:

这是我的 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;
    }


}

The value in tr.url is "rt.setUrl" not the value in application.properties?

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

采纳答案by ssn771

I'm not 100%, but I think your @PropertySourceisn't quite right. Instead of

我不是 100%,但我认为你@PropertySource的说法不太对。代替

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

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

It should just be:

它应该只是:

@PropertySource("classpath:application.properties")

@PropertySource("classpath:application.properties")

based on this:

基于此:

Spring PropertySource Documentation

Spring PropertySource 文档

Also, based on the link above and since you have mentioned you were converting to a java config approach instead of xml, I think the below might be the solution to your issue:

此外,基于上面的链接,并且由于您提到您正在转换为 java 配置方法而不是 xml,我认为以下可能是您问题的解决方案:

Resolving ${...} placeholders in and @Value annotations In order to resolve ${...} placeholders in definitions or @Value annotations using properties from a PropertySource, one must register a PropertySourcesPlaceholderConfigurer. This happens automatically when using in XML, but must be explicitly registered using a static @Bean method when using @Configuration classes. See the "Working with externalized values" section of @Configuration Javadoc and "a note on BeanFactoryPostProcessor-returning @Bean methods" of @Bean Javadoc for details and examples.

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

The example from the link above is how I normally do it:

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

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

So add at the top:

所以在顶部添加:

@Autowired
Environment env;

Then in your method use:

然后在你的方法中使用:

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

and so on for the remaining property values. I am just not as familiar with the way you are doing it. I know the above approach will work though.

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

回答by dimitrisli

Aside from @ssn771 answer that involves injecting the Environmentand retrieving the properties through it which is indeed the suggested way of doing it, this is what I've done as a workaroundwithout having to change the way @Valueis being used in the @ConfigurationPOJO.

除了@ssn771 答案涉及注入Environment并通过它检索属性这确实是建议的执行方式之外,这就是我作为一种解决方法所做的,而不必更改@Value@ConfigurationPOJO中使用的方式。

回答by Anton Koscejev

Out of the many suggested things the most important one is that you need to configure PropertySourcesPlaceholderConfigurerin Spring 3.1+ (or PropertyPlaceholderConfigurerin Spring 3.0). It must be staticif you want it to be applied to the configuration class (to use @Valueannotations).

在许多建议的事情中,最重要的是您需要PropertySourcesPlaceholderConfigurer在 Spring 3.1+(或PropertyPlaceholderConfigurerSpring 3.0)中进行配置。它必须是static,如果你希望它被应用于配置类(以使用@Value注释)。

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

From javadoc for PropertySourcesPlaceholderConfigurer :

来自 PropertySourcesPlaceholderConfigurer 的 javadoc:

This class is designed as a general replacement for PropertyPlaceholderConfigurer in Spring 3.1 applications. It is used by default to support the property-placeholder element in working against the spring-context-3.1 XSD, whereas spring-context versions <= 3.0 default to PropertyPlaceholderConfigurer to ensure backward compatibility. See the spring-context XSD documentation for complete details.

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