在spring4.0之后,要使用注解开发,需要保证导入了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/>
<context:component-scan base-package="XXX.XXX.XXX"/>
</beans>
指定要扫描的包,这个包下面的注解就会生效
<!---->
<context:component-scan base-package="XXX.XXX.XXX"/>
@component注解
有这样一个简单的实体类:
public class User {
public String name="滔滔";
}
在该类上面加上@component注解,等价于
<bean id="user" class="com.tt.pojo.User"/>
即不用在配置文件里写bean标签了
@Component //等价于 <bean id="user" class="com.tt.pojo.User"/>
public class User {
public String name="滔滔";
}
@Value注解 —属性值的注入
把上面的类修改一下,不给变量赋值:
@Component
public class User {
public String name;
}
因为String类型默认是null,所以测试输出没有任何结果,可以在该属性上增加一个@Value(“XXX”)注解赋值:
@Component
public class User {
@Value("滔滔")
public String name;
}
ps:如果类中有set()方法,该注解也可以用在set()方法上。
衍生的注解
@Component有几个衍生注解,在web开发中,会按照MVC三成架构分层。
- dao层:@Repository
- service层:@Service
- controller层:@Controller
这四个注解的功能都是一样的,都是代表将某一个类注册到spring容器中,装配bean.
小结:
xml与注解的最佳实践:
- xml用来管理bean.
- 注解只负责完成属性的注入.