在spring4之后,如果要使用注解进行开发,得确认在maven中aop包是否导入
这里导入的为spring-webmvc这个依赖会自动导入一系列的spring所需要的支持,非常方便
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
</dependencies>
使用注解需导入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:component-scan base-package=""/>
<!--增加注解驱动支持-->
<context:annotation-config/>
</beans>
注解说明:
@Autowired:自动装配通过类型匹配,通过byType
方式实现,如果Autowired不能自动装配上属性,则需要通过@Qualifier(value="xxxx")
@Nullable:字段标记了这个注解,说明这个字段可以为null
@Resource:默认通过byName的方式实现,如果找不到名字则通过byType方式实现两个都找不到就报错
@Component:组件放在类上说明这个类被spring管理了
衍生的注解
@Component:有几个衍生注解,我们在web开发中,按照mvc三层架构分层
- dao【@Repository】
- service【@Service】
- controller 【@Controller】
这四个注解功能都是一样的,只是为了区分web开发层级,其功能都是将类注册到spring中
@Scope("")
这个注解里面的value 可以填singleton代表单例模式,也可以填prototype代表原型模式
6、xml和注解
xml更加万能,适用于任何场合
注解不是自己的类使用不了,维护相对复杂
xml与注解的最佳实践:
xml用来管理bean
注解只负责完成属性的注入
我们在使用的过程中,需要注意一个问题:必须要让注解生效,就需要开启注解的支持
<!--指定扫描的包,这个路径下的包注解就会生效-->
<context:component-scan base-package=""/>
<!--增加注解驱动支持-->
<context:annotation-config/>