1.IOC(控制反转)注解
Spring框架中有注解和XML两种配置方式,包括Spring中的IOC和AOP也一样,
都有XML和注解两种方式
1.XML配置:
优点:1.降低了耦合,修改配置文件不需要工程进行修改和重新编译
2.适合处理大量业务
缺点:花费时间,过多时难以管理
2.annotation配置
优点:1.在class文件中,可以降低维护成本,annotation的配置机制很明显简单
2.不需要第三方的解析工具,利用java反射技术就可以完成任务
3.编辑期可以验证正确性,查错变得容易
4.提高开发效率
缺点:1.如果对annotation修改,需要重新编译整个工程
2.业务类之间关系不如XML配置那样容易把握
注解注入步骤
1.导包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
2.创建xml文件
<?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="需要扫描的包名"/> //重要的地方1,想扫描哪写到哪
</beans>
3.业务类
//类名上添加Component注解
@Component //重要的地方2
public class UserService {
private IUserDao userDao;
//需要注入的变量上添加@Autowired
@Autowired
public void setUserDao(IUserDao userDao) {
this.userDao = userDao;
}
}
//获取bean时需要类名小驼峰
application.getBean("addressServiceImpl") //重要的地方3 小驼峰
@Autowired(自动封装)
加在set方法上会通过setter方法进行注入,写在变量上直接通过反射设置变量值
默认使用byType匹配,,若有多个同一类型对象,更改为byName匹配根据set方法
对应的参数列表的局部变量名来匹配,找不到就报错。
@Autowired(required=false)说明值可以为null,找不到不会报错。(默认为true)
@Qualifier("bean名字"):以指定名字进行匹配
@Resource(name=" "),:默认使用byName,匹配set方法名字,不行再匹配方法参数列表的名字,再不行就转换为byType根据类型匹配
当然也可以指定名字,相当于Autowired和Qualifier连用
注解分类:
@Controller :WEB 层 ,就是和页面交互的类
@Service :业务层 ,主要处理逻辑
@Repository :持久层 ,就是Dao操作数据库
这三个注解是为了让标注类本身的用途清晰,Spring 在后续版本会对其增强
@Component: 最普通的组件,可以被注入到spring容器进行管理
@Value :用于注入普通类型. 可以写在变量上和setter方法上
@Autowired :自动装配,上面描述比较详细,可以参照上面
@Qualifier:强制使用名称注入.
@Resource 相当于: @Autowired 和@Qualifier 一起使用
@Scope: 设置对象在spring容器中的生命周期
取值 :
singleton:单例
prototype:多例
@PostConstruct :相当于 init-method
@PreDestroy :相当于 destroy-method
注解含义:
@Component 最普通的组件,可以被注入到spring容器进行管理
@Repository 作用于持久层
@Service 作用于业务逻辑层
@Controller 作用于表现层(spring-mvc的注解)