您现在的位置是:首页 > 文章详情

Spring的component-scan可配置化

日期:2018-11-06点击:660

本文是基于Spring4.3.5.RELEASE的版本进行的分析和实践

在Spring的web项目里面, 如果我们需要在类似 applicationContext.xml里面加上

<context:component-scan base-package="${component.scan.package}" /> 

让base-package可配置, 那应该怎么做呢?

1. 加到Jvm的启动参数里面

比如

-Dcomponent.scan.package=com.example.yours 

这里面有两个不方便的地方:

1.多个属性的话, 一个个加启动参数不方便,

2.修改了属性的值,也需要一个个修改对应的启动参数

2. 加到ServletContext里面

import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Map.Entry; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.web.context.ContextLoaderListener; public class SingleWebContextLoaderListener extends ContextLoaderListener { private static final String DEFAULT_ENCODING = "UTF-8"; private static final String[] SPRING_PROPERTIES_FILE_NAME = new String[] {"classpath:property1.properties"}; @Override public void contextInitialized(ServletContextEvent event) { initPropertySources(event.getServletContext(), SPRING_PROPERTIES_FILE_NAME); super.contextInitialized(event); } private void initPropertySources(ServletContext servletContext, String... resourcesPaths) { ResourceLoader resourceLoader = new DefaultResourceLoader(); Properties props = new Properties(); for (String location : resourcesPaths) { Resource resource = resourceLoader.getResource(location); try (InputStream is = resource.getInputStream()){ props.load(new InputStreamReader(is, DEFAULT_ENCODING)); } catch (IOException ex) { ex.printStackTrace(); } } for(Entry<Object, Object> e : props.entrySet()) { servletContext.setInitParameter((String)e.getKey(), (String)e.getValue()); } } } 

然后在web.xml把原来的ContextLoaderListener 替换成SingleWebContextLoaderListener

<listener> <listener-class>xx.xx.SingleWebContextLoaderListener</listener-class> </listener> 

当然如果你需要用到 ${}这种变量的话, 别忘了加

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"/> 

上面说明的两种方法, 都是比较方便的, 如果你对spring的源代码比较熟悉的话, 可以自己定一个ApplicationContext, 去实现

如果大家需要了解里面的原理的话, 可以留言, 我们再开一个帖子来解释一下

原文链接:https://my.oschina.net/cmaj135/blog/2872360
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章