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

标签 java spring spring-mvc

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

这是我的网络配置:

@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 中的值?

最佳答案

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

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

它应该只是:

@PropertySource("classpath:application.properties")

基于此:

Spring PropertySource Documentation

此外,根据上面的链接,由于您提到要转换为 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.

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

 @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 - bean 中的 Spring JavaConfig 属性未设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15478806/

相关文章:

java - 什么可能导致 JVM 崩溃并显示 SIGSEGV "ClassLoaderData::metaspace_non_null()"

java - Tomcat 提示 spring-security-3.1.xsd 不匹配 Spring Security 3.2,但没有在任何地方引用 3.1

java - ActiveMQ 中的主题创建

java - 向 Java 类添加方法是否会增加其实例的内存使用量?

java - 在 spring security + spring boot 中禁用同一用户的多个登录

java - SLF4J和Logback : Propagate logger to autowired services

hibernate - 解释 Struts 2、Spring 和 Hibernate 集成的教程

java - 从 JPA 类自动创建表

java - POM.xml 中的 tomcat 资源错误

java - 跟踪 java 分析器中的最大内存使用