Spring的组件扫描
Spring2.0以后的版本中,引入了基于注解(Annotation)的配置。注解是JDK1.5的一个新特性。XML配置灵活。注解和XML可以配合使用。 [b]1. Spring的注解支持:[/b] 在spring的配置文件中引入context的Schema命名空间,并添加注解配置标签: [code="xml"] [/code] 实例: [code="java"] public class Jurisdiction { public void juristic() { System.out.println("juristic() is executed!"); } } [/code] [code="java"] public class Vegeterian { @Autowired Jurisdiction jurisdiction; public void maigre() { System.out.println(jurisdiction); } } [/code] beans-context.xml [code="xml"] [/code] 测试方法: [code="java"] @Test public void testAnnotationConfig() { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans-context.xml"); Vegeterian vegeterian = ctx.getBean("vegeterian", Vegeterian.class); vegeterian.maigre(); } [/code] 输出为null。 在beans-context.xml中添加 [code="xml"] [/code] 重新测试,输出不为null [b]2. Spring扫描包:[/b] 如果有很多的包和类,在XML文件中配置稍显繁杂,且要控制哪些包或类需要由Spring实例化时,可以使用包扫描方式。 扫描后,放入spring容器,交由spring管理 [code="xml"] [/code] 支持添加移除子包 [code="xml"] [/code] 说明: [list] 1. exclude-filter先于include-filter解析,include-filter不会包括被exclude-filter剔除的包 2. include-filter在exclude-filter之后定义会报SAXException异常 [/list] 如何剔除一部分包,并保留其它的包: a. 使用aspect的语法,将剔除和包括放在一个filter表达式里面: [code="xml"] [/code] 支持下面几种语法: [table] |Filter Type | Example Expression | Description |annotation | org.example.SomeAnnotation | 标注有SomeAnnotation的类 |custom | org.example.MyTypeFilter | Spring3新增自定义过滤器,实现org.springframework.core.type.TypeFilter接口 [/table] 测试: [code="java"] @Controller public class MyController { } @Service public class MyService { } [/code] component-scan-test.xml [code="xml"] [/code] [code="java"] public class ComponentScanTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring/core/context/component-scan-test.xml"); //MyController myController = context.getBean("myController", MyController.class); MyService myService = context.getBean("myService", MyService.class); } } [/code] 注意: 如果类型为regex,'\'为转义符,'.'代表任意字符,'*'表明前面的字符出现0或多次,'..'在这里并不代表子包。 类型为aspectj,'\','.','*'都代表自己本身,'..'代表子包 [b]3. 属性注入方式:[/b] @Resource 默认按名称装配,当找不到与名称匹配的bean才会按类型装配。 @Autowired 默认按类型装配 [b]4. bean的作用域[/b] [list] 1. singleton 2. prototype 3. request 4. session [/list] 默认的作用域为singleton 可以在xml中配置bean的scope属性为prototype,或Bean上加@Scope("prototype")注解,这样每次getBean拿到的都是新创建的实例: 如: [code="xml"] [/code] [code="java"] public class SingletonBean { } public class PrototypeBean { } public class ScopeTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring/core/scope/scope-test.xml"); SingletonBean singleton1 = context.getBean(SingletonBean.class); SingletonBean singleton2 = context.getBean(SingletonBean.class); System.out.println(singleton1 == singleton2); // true PrototypeBean prototype1 = context.getBean(PrototypeBean.class); PrototypeBean prototype2 = context.getBean(PrototypeBean.class); System.out.println(prototype1 == prototype2); // false } } [/code]