配置PropertySourcesPlaceholderConfigurer / resource文件夹的最佳方法是什么?

时间:2016-06-14 08:15:48

标签: java spring

我有一个(gradle / java / eclipse)项目,在我看来是一个非常标准的文件夹结构

...main
  java
  ...controller
  ...service
  resources
  webapp
  ...resources
  WEB-INF

我遇到了一个我不明白的问题,尽管我已经以非常混乱的方式解决了这个问题。如果我在WebMvcConfigurerAdapter的组件扫描中指定controllers文件夹,则服务类无法使用配置的PropertySourcesPlaceholderConfigurer bean获取属性。如果我扩大组件扫描出jsp文件,请不要选择css包含!

所以使用这个配置类一切都很好,但是在服务实现类

中没有解析属性

配置类

@EnableWebMvc
@Configuration
@ComponentScan({ "comm.app.controller" })
@PropertySource({ "classpath:app.properties" }) 
public class SpringWebConfig extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/views/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

//used to handle html put and delete rest calls
@Bean(name = "multipartResolver")
public CommonsMultipartResolver createMultipartResolver() {
    CommonsMultipartResolver resolver=new CommonsMultipartResolver();
    resolver.setDefaultEncoding("utf-8");
    return resolver;
}

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

}

服务实施课程开始

@Service("appService")
@PropertySource({ "classpath:app.properties" })
public class appServiceImpl implements appService {

private RestTemplate restTemplate = new RestTemplate();

@Value("${property.reference}")
private String propref; 

   ...

在这种情况下,$ {property.reference}未被选中,但视图页面样式(从... webapp \ resources ... .css中选取)很好。

如果我改变

  @ComponentScan({ "comm.app.controller" }) 

  @ComponentScan({ "comm.app" })

拾取属性(可能是因为propertyConfig bean进入范围?)但是找不到本地样式文件?任何对文件webapp \ resources ... .css的链接引用都会失败。

最后,我找到了一个糟糕的(!?)解决方案

1)保持@ComponentScan({“comm.app.controller”})的范围

2)将serviceimplementation类破解为......

@Configuration
@Service("appService")
@PropertySource({ "classpath:app.properties" })
public class appServiceImpl implements appService {

private RestTemplate restTemplate = new RestTemplate();


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

@Value("${property.reference}")
private String propref; 

   ...

有人能告诉我,我是否已经错误地配置了资源文件的路径,或者可能应该使用propertyConfig bean做一些不同的事情? (可能是在另一个配置文件中注入或声明另一个?)

0 个答案:

没有答案