Spring源码的Bean管理之注解方式
1 什么是注解?
1 注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值…)
2 使用注解,注解作用在类上面,方法上面,属性上面
3 使用注解目的:简化 xml 配置
2 Spring中创建对象提供注解
-
@Component
-
@Service
-
@Controller
-
@Repository
3 对象创建案例
1 引入依赖
spring-aop-5.2.6.RELESE.jar
2 开启组件扫描
<!--开启组件扫描
1 如果扫描多个包,多个包使用逗号隔开
2 扫描包上层目录
-->
<context:component-scan base-package="com.cf"></context:component-scan>
3 在创建类上添加注解
@Component(value = "userService")
// 等同于 <bean id="userService" class=".."/>
public class UserService {
public void add() {
System.out.println("service 新增.......");
}
}
4 开启组件扫描
<!--示例 1
use-default-filters="false" 表示现在不使用默认 filter,自己配置 filter
context:include-filter ,设置扫描哪些内容
-->
<context:component-scan base-package="com.cf" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--示例 2
下面配置扫描包所有内容
context:exclude-filter: 设置哪些内容不进行扫描
-->
<context:component-scan base-package="com.cf">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
5 注解方式注入
1 @Autowired
根据属性类型进行自动装配
@Service
public class UserService {
// 定义 dao 类型属性
// 不需要添加 set 方法
// 添加注入属性注解
@Autowired
private UserDao userDao;
public void add() {
System.out.println("service 新增.......");
userDao.add();
}
}
2 @Qualifier
根据名称进行注入
// 添加注入属性注解
// 根据类型进行注入
@Autowired
// 根据名称进行注入
@Qualifier(value = "userDaoImpl1")
private UserDao userDao;
3 @Resource
可以根据类型注入,可以根据名称注入
// @Resource //根据类型进行注入
@Resource(name = "userDaoImpl1")
// 根据名称进行注入
private UserDao userDao;
4 @Value
注入普通类型属性
@Value(value = "abc")
private String name;
6 注解开发案例
1 配置类
替代xml配置文件
// 作为配置类,替代 xml 配置文件
@Configuration
@ComponentScan(basePackages = {"com.cf"})
public class SpringConfig {
}
2 测试类
@Test
public void testService2() {
// 加载配置类
ApplicationContext context
= new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = context.getBean("userService",
UserService.class);
System.out.println(userService);
userService.add();
}