2015年11月27日星期五

context:property-placeholder vs PropertySourcesPlaceholderConfigurer

spring各个版本还不一样,目前最新的是

3.1前,property-placeholder 解析为 PlaceholderConfigurerSupport
3.1后,property-placeholder 解析为PropertySourcesPlaceholderConfigurer

关于父子容器
父亲里面定义的property-placeholder,儿子里面@Value读不到。

要想多个 property-placeholder,需要设置ignore-unresolvable="true" ,顺序靠order,但是是以order小的优先。比如order1先加载了keyA=valueA,order2里面如果有keyA=valueAA,order2里面的keyA=valueAA不会加载,所以内容仍然是order1里的valueA。

property-placeholder定义的内容进不了Environment,所以env.getProperty是拿不着东西,就算@Value拿到了也不行。

挺乱。


结论就是,不要再使用 property-placeholder了,以后要用 @PropertySource
 @PropertySource自己并不会注册PropertySourcesPlaceholderConfigurer ,所以需要自己定义一个PropertySourcesPlaceholderConfigurer bean
 @PropertySource的父子容器是
父亲定义的,儿子可以读取,@Value可以读,env可以读。
同一个容器里的多个 @PropertySource,就拼先后顺序了。

2015年11月13日星期五

spring的豆知识

http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch06s02.html 

<context:annotation-config/>,@AnnotationDrivenConfig
AnnotationConfigApplicationContext来实现的。有了它可以使用
@Configuration,@Bean然后

@Resource 、@PostConstruct、@PreDestroy
@PersistenceContext
@Autowired
@Required
@Autowired就有了注入功能。不用再写ref=xxx了。自身并不创建bean。
<context:component-scan>@ComponentScan,包含了component-scan所有的功能,另外加上了扫描到的Component的自动创建注册功能。@Component(以及后代@Repository,@Service,@Controller,@RestController)都创建起来了。

这里@Configuration其实已经注解了@Component了,它其实也是@Component的后代。


<mvc:annotation-driven />@EnableWebMvc,@RequestMapping起作用了。提供了mvc里面的req到controller的mapping功能,没有它reqdispatch不到controller,也就是找不着dispatch的对象。它对应JavaConfig里的@EnableWebMvc。当然相关的Mvc的配置也跟着就被调用了,如WebMvcConfigurerAdapter.configureContentNegotiation。


WebApplicationInitializer(AbstractAnnotationConfigDispatcherServletInitializer)相关的是启动时会被扫描,然后加载配置类,是完全拥有自己的Container(ServletContext)的。

配置类,
如果Initialize加载,就去配置Initializer里面创建的上下文ConfigWebApplicationContext属性,然后上下文属性在作用到里面创建的servlet(DispatcherServlet),当然一个ConfigWebApplicationContext可以创建多个servlet,也就是同一份配置,应用到了多个servlet,这些servlet共享一个上下文,也就是同一个Container里面的不同servlet共享bean了。

如果是被web.xml里面指定的servlet的ComponeScan扫描到,就去配置当前servlet的上下文,这里不会再次创建上下文,所以@Configure的类只是对已有的配置进行再配置。如果同一个servlet扫描到多个@Configure怎么办?我认为是后面的进一步补充前面的。

配置类里想要知道 自己被应用到哪些SerletContext了?我没找到方法。

另外,这些配置是不会被子container给继承的,比如root containter定义了<mvc:annotation-driven />,它的child仍然需要定义。

http://techidiocy.com/annotation-config-vs-component-scan-spring-core/
http://www.cnblogs.com/fangqi/archive/2012/11/04/2748579.html 
http://stackoverflow.com/questions/7414794/difference-between-contextannotation-config-vs-contextcomponent-scan