在Spring4之后,要使用注解开发,但是必须保证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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解支持-->
<context:annotation-config/>
</beans>
1.bean注解
@Component
放在类上,说明这个类被Spring管理了,就是Bean,相当于下面的bean:
<bean id="user" class="com.kuang.pojo.User"/>
@Component
public class User {
public String name="zhangsan";
}
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解支持-->
<context:annotation-config/>
<!--指定要扫描的包,这个包下面的注解就会生效-->
<context:component-scan base-package="com.kuang.pojo"/>
</beans>
@Component有几个衍生注解,在web开发中,按照mvc三层架构分层
- dao----->@Repository
- service---->@Service
- controller—>@Controller
这四个注解功能都是一样的,代表将某个类注册到Spring中,装配Bean
2.属性注解
@Value(“狂神”):相当于下面的,可以放在属性或者setter方法上
<property name="name" value="狂神"/>
@Component
public class User {
@Value("狂神")
public String name;
}
3.自动装配注解(上个博客已讲)
@Autowired:自动装配通过name和type
@Qualifier:通过name和type匹配不上再使用
@Resource:自动装配通过name匹配
4.作用域注解
@Scope(value = “singleton”)
@Component
@Scope(value = "singleton")
public class User {
@Value("狂神")
public String name;
public void setName(String name) {
this.name = name;
}
}
5.总结
xml与注解的最佳实践:
- xml赋值管理bean
- 注解负责完成属性的注入