①在Spring之后, 要使用注解开发, 必须要保证aop的包导入了

②使用注解要导入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>
③指定要扫描的包, 这个包下的注解就会生效<**context:component-scan base-package="com.pojo"**/>
<?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"/>
<context:annotation-config/>
</beans>
8.1、bean
@Component : 组件, 放在类上, 说明这个类被Spring管理了, 就是bean!_
等价于: _
//@Component 组件
@Component //等价于: <bean id="user" class="com.pojo.User"/>
public class User {
8.2、属性如何注入
@Value(“属性值”) : 注入属性值, 放在属性或者Set方法上
_ 等价于: _
//@Component 组件
@Component //等价于: <bean id="user" class="com.pojo.User"/>
public class User {
@Value("情伤难合")//等价于: <property name="name" value="身伤易逝"/>
public String name ;
}
8.3、衍生的注解
@Component 有几个衍生注解, 我们在web开发中, 会按照MVC三层架构分层!
①dao [@Repository**]
②service [@Service]
③controller [@Controller]**
这4个注解功能完全一样, 都是代表将某个类注册到Spring中, 装配Bean
8.4、自动装配
@Autowired : 自动装配(通过类型、名字), 用在属性或Set方法上
如果@Autowired不能自动装配上属性, 则需通过@Qualifier(value = “XXX”)去配置
@Nullable : 如果标记了这个注解, 说明这个字段可以为"null", 用在属性上
@Resource : 通过名字、类型实现自动装配, 用在属性或Set方法上
8.5、作用域
@Scope(“singleton”) //标注该类是单例模式 prototype: 原型模式
用在类上(要与@Component 连用)
8.6、小结
xml与注解 :
①xml更加万能, 适用于任何场合! 维护简单方便
②注解 不是自己的类就无法使用(不好引用), 维护相对复杂
xml与注解的最佳实践 :
①xml用来管理bean
②注解只负责属性的注入(@Value(“属性值”))
③使用的过程中只需要注意一个问题:
必须让注解生效(开启注解的支持和扫描包)