在spring4之后,想要使用注解形式,
-
必须得要引入aop的jar包
-
在配置文件当中,还得要引入一个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:annotation-config/>
</beans>
1. 代替bean--------@Component
- 放在实体类上,说明这个类被Spring管理了
//@Component等价于<bean id="user" class="com.qk.pojo.User"></bean>
@Component
public class User {
public String name = "qk";
}
2. 代替property--------@Value
- @Value 等价于 < property name=“name” value=“35s”>
- 放在set方法上,也可以为set方法注入属性值
3. @Component的衍生注解
- 在web开发中,一般会按照三层架构分层
- dao -------- @Repository
- service --------@Service
- controller --------@Controller
- 这几个注解和@Component的功能一样,都是代表将某个类注册到spring容器中,装配bean。只是因为在不同的层,所以名字不一样。
4. 自动装配
- 略
5. 作用域
- 略
6. 小结
xml与注解:
- xml更万能,适用于任何场合,维护简单方便
- 注解不是自己的类使用不了,开发简单方便,维护相对复杂
xml与注解整合开发 :推荐最佳实践
- xml来管理Bean
- 注解用来完成属性注入
- 使用过程中, 可以不用扫描,扫描是为了类上的注解