1.在spring4之后,要使用注解开发,必须要导入aop包,只需导入spring-webmvc依赖里边包含了这个包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
2.在配置文件中,需要确定context的约束是否正确,再进行配置
- 导入约束:
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
https://www.springframework.org/schema/context/springcontext.xsd"
- 进行配置
<!--指定要扫描的包这个包中类的注解会生效-->
<context:component-scan base-package="com.fsp.pojo"/>
<!--配置注解的支持-->
<context:annotation-config/>
即:
<?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
https://www.springframework.org/schema/context/spring-context.xsd">
<!--指定要扫描的包这个包中类的注解会生效-->
<context:component-scan base-package="com.fsp.pojo"/>
<!--配置注解的支持-->
<context:annotation-config/>
</beans>
3.在相应的类及属性上进行注解
//注入类,放在类前
@Component
public class User {
//注入属性值,放在属性前
@Value("fsp")
public String name;
}
@Component放在类上:指定要扫描包中的类会生效
@Value("")放在属性上,进行赋值
@Autiwired放在引用类型,即对象前
4.注解的衍生:
@Component(扫描包中的类)有几个衍生的注解,在dao、service、controller上作用都一样:
- dao:[@Repository]
- service:[@Service]
- controller:[@Conrtoller]