IOC容器 Bean管理 注解方式配置
注解
注解配置方法之需要将相应注解添加到类上方即可定义一个Bean对象
主要注解
- @Component
- @Service
- @Controller
- @Repository
这四个注解功能都是相同的,只是用于在不同模块中区分作用而已。
实现
用法
在类上方添加四个中的任意一个就可以创建一个Bean对象
示例:
@Service(value = "service")
public class UserService {
public void add(){
System.out.println("OK");
}
}
如实例中首行的@Service(value = “service”)
括号中的value是bean的ID属性
等同于XML中Bean标签的id属性
如果不定义value,只写@Service。那么Spring默认使用类名称作为Bean名称。
XML配置
注解只是简化XML配置,所以仍然需要配置XML文件。
由于注解直接定义在源文件,所以需要在XML中指定Spring去扫描注解以在启动时创建Bean实例。
context空间名称用于扫描
XML配置:
<context:component-scan base-package="AnnotationSpring.baseAnnotation"/>
- context:component-scan:扫描容器
- base-package:指定要扫描的包
测试:
TestDemo
public class TestDemo {
@Test
public void test(){
ApplicationContext context =
new ClassPathXmlApplicationContext("AnnotationSpring.xml");
UserService service =
context.getBean("service", UserService.class);
service.add();
}
}
输出
OK
进程已结束,退出代码0
XML配置细节
示例1
<context:component-scan base-package="AnnotationSpring" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
- use-default-filters=“false”:关闭默认扫描器
- context:include-filter:引入自定义扫描器
- type=“annotation”:定义扫描类型为Annotation注解
- expression:注解的完整路径
此XML含义为:关闭默认扫描器(默认扫描器扫描所有注解),引入自定义扫描器。自定义扫描器指定金扫描定义为@Controller注解的类
示例2
<context:component-scan base-package="AnnotationSpring">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
- context:exclude-filter:在扫描时忽略某些配置
- type=“annotation”:忽略的类型为注解
- expression:要忽略的注解类型的完整路径
此XML含义:使用默认扫描器扫描全部,但扫描时不包含声明的属性。即扫描全部但不扫描声明为@Controller注解的类