使用注解之前必须要先指定扫描指定包,而指定约束的空间不在之前xml的空间在context空间和约束中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.serive"/>
</beans>
注解分为四类
用于创建对象
用于注入数据
注解
@component:作用把当前类存入容器中
属性value指定id的值
以下三个注解和@component作用一样,只是制订了MVC三层的使用
@Controller
@Service
@Repository
注入数据的注解
@Autowired
作用:自动按照类型注入,只要容器中有唯一的一个bean对象类型与其对应成功。出现位置:成员,方法上。如果有多个类型相同(集成同一个接口“)可以通过变量名指定 spring容器中的id
@Qualifier标签作用于@Autowired标签下,或者参数指定类型
@Autowired
@Qualifier("idao")
@Resource(name = "idao")用于注入指定id类型
以上三个都用于指定注入bean类型对象,而基本类型和string类型不能使用,另外集合类型注入只能通过xml来注入
@Value("16")
@Value("16")
int i;
用于指定基本和String类型和SpEL ¥{表达式}
用于改变作用范围
Scope
用于指定改变作用范围
属性 value 常用取值 prototype和singleton
用于作用生命周期
@PreDestroy:销毁方法
@PostConstruct:初始化方法
网友评论