一、注解基础概念
1.什么是注解编程
指的是在类或者方法上加入特定的注解(@xxx),完成特定功能的开发。
@Component
public class XXX{}
2.为什么需要注解编程
1.注解开发方便
代码简洁、开发速度大大提高
2.Spring开发潮流
Spring2.x引入注解 Spring3.x完善注解 SpringBoot普及 推广注解编程
3注解的作用
-
替换XML这种配置形式,简化配置
-
替换接口,实现调用双方的契约性
通过注解的方式,在功能调用者和功能提供者之间达成约定,进而进行功能的调用。因为注解应用更为方便灵活,所以在现在的开发中,更推荐通过注解的形式,完成。
4.Spring注解的发展历程
1.Spring2.x开始支持注解编程 @Commponent @Service @Scope。。
目的:提供这些注解只是为了在某些情况下简化XML的配置,作为XML开发的有益补充。
2.Spring3.x @Configuration @Bean..
目的:彻底替换XML,基于注解编程
3.Spring4.x SpringBoot诞生
提倡使用注解常见开发
5.Spring注解开发中的一个问题
Spring基于注解进行配置后,还能否解耦合呢?
在Spring框架应用注解时,如果能对注解配置的内容不满意,可以通过Spring配置文件进行覆盖的
二、Spring的基础注解(Spring2.x)
这个阶段的注解,仅仅是简化XML的配置,并不能完全替代XML
1.对象创建相关注解
-
搭建开发环境
<context:component-scan base-package="com.spring"/> 作用:让Spring,框架在设置包及其子包中扫描对应的注解,使其生效
-
对象创建相关注解
- @Commponent
作用:替换原有Spring配置文件中的<bean标签
注意:
id属性— component注解提供了默认的设置方法>首单词首字母小写
class属性— 通过反射获得class内容
- @Commponent
- @Component细节
①如何显示指定工厂创建对象的id值
②Spring配置文件覆盖注解配置内容@Component("u")
applicationcontext.xml <bean id="u" class="com.xxx.xxx.User"/> id值 class值 要和注解中的保持一致
- @Component的衍生注解
@Repository --->DAO @Repository public class xxxDAO(){ } @Service --->Service @Service public class xxxService(){ } @Controller ---Action/Controller @Controller public class xxxController 注意:本质上这些衍生注解就是@Component 作用 <bean 细节 @Service("s") 目的:更加准确的表达一个类型的作用 注意:Spring整合Mybatis开发过程中不使用@Repository @Component
- @Scope注解
作用:控制简单对象创建次数 注意:不添加@Scope Spring提供默认值 singleton单例 多例值:prototype <bean id="xx" class="" scope="singleton|prototype"
- @Lazy注解
作用:延迟创建单实例对象 注意:一旦使用@Lazy注解后,Spring会在使用这个对象的时候,进行这个对象的创建 <bean id="" class="" lazy="false"/>
- 声明周期方法相关注解
1.初始化相关方法@PostConstruct 实现InitializingBean接口 <bean init-method=""/> 2.销毁方法@PreDestroy 实现DisposableBean <bean destory-method=""/> 注意:(1)上述的两个注解并不是Spring提供的,JSR(JavaEE规范)250 (2)再一次的验证,通过注解实现了接口的契约性
2.注入相关注解
- 用户自定义类型 @Autowired
@Autowired细节
1.Autowired注解基于类型进行注入【推荐】
基于类型的注入:注入对象的类型,必须与目标成员变量类型相同或者是其子类(实现类)
2.Autowired Qualifier 基于名字进行注解【了解】
基于名字的注入:注入对象的id值,必须与Qualifier注解中设置的名字相同
3.Autowired注解放置位置
①放置在对应成员变量的set方法上。
②直接把这个注解放置在成员变量之上,Spring通过反射直接对成员变量进行注入(赋值)【推荐】
4.javaEE规范中类似功能的注解
JSR250 @Resource(name=”userDAOImpl“)基于名字进行注入
@Autowired()
@Qualifier("userDAOImpl")
注意:如果在应用Resource注解时,名字没有配对成功,那么他会继续按照类型进行注入。
JSR330 @Inject 作用@Autowired完全一致 基于类型进行注入--->EJB3.0
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
-
JDK类型
@Value注解完成 1.设置xxx.properties id=10 name=bugz 2.Spring的工厂读取这个配置文件 <context:property-placeholder location="classpath:xxx.properties"/> 3.代码 属性@Value("${key}")
- @PropertySource
1.作用:用于替换Spring配置文件中的<context:property-placeholder location=""/>标签 2.开发步骤 (1)设置xxx.properties id=10 name=bugz (2)应用@PropertySource (3)代码 属性@Value()
- @Value
①、@Value注解不能应用在静态成员变量上如果应用,赋值(注入)失败
②、@Value注解+Properties这种方式不能注入集合类型
Spring提供新的配置形式 YAML YML(SpringBoot)
3.注解扫描详解
<context:component-scan base-package="com.spring"/>
当前包及其子包
(1)排除方式
<context:component-scan base-package="com.spring">
<context:exclude-filter type="assignable" expression=""/>
type="assignable"排除指定的类型不进行扫描
type="annotation"排除特定的注解不进行扫描
type="aspectj"切入点表达式
包切入点:com.baizhiedu.bean..*
类切入点:*..User
type="regex"正则表达式
type="custom"自定义排除策略框架底层开发
</context:component-scan>
排除策略可以叠加使用
<context:component-scan base-package="com.spring">
<context:exclude-filter type="assignable" expression="com.spring.annotation1.User"/>
<context:exclude-filter type="aspectj" expression="com.spring.*"/>
</context:component-scan>
(2)包含方式
<context:component-scan base-package="com.spring" use-default-filters="false">
1.use-default-filters="false"
作用:让Spring默认的注解扫描方式失效。
2.<context:include-filter type="" expression=""/>
type="assignable"排除指定的类型进行扫描
type="annotation"排除特定的注解进行扫描
type="aspectj"切入点表达式
包切入点:com.baizhiedu.bean..*
类切入点:*..User
type="regex"正则表达式
type="custom"自定义包含策略框架底层开发
</context:component-scan>
包含的方式支持叠加
<context:component-scan base-package="com.spring" use-default-filters="false">
<context:include-filter type="assignable" expression="com.spring.annotation1.User"/>
<context:include-filter type="aspectj" expression="com.spring.*"/>
</context:component-scan>
4.对于注解开发的思考
- 配置互通
Spring注解配置 配置文件的配置 互通
@Repository
public class UserDAOImpl{
}
public class UserServiceImpl{
private UserDAO userDAO;
set get
}
<bean id="userService" class="com.xxx.UserServiceImpl">
<property name="userDAO" ref="userDAOImpl"/>
</bean>
- 什么情况下使用注解 什么情况下使用配置文件
@Component 替换<bean>
基础注解(@Component @Autowired @Value)程序员开发类型的配置
1.在程序员开发的类型上可以加入对应注解进行对象的创建
Entity Service DAO Controller
2.应用其他非程序员开发的类型时,还是需要使用<bean 进行配置的
SqlSessionFactoryBean MapperScannerConfigure
5.SSM整合开发(半注解版)
略~~~~
三、Spring的高级注解(Spring3.x及以上)
1.配置bean
Spring在3.x提供新的注解,用于替换XML配置文件。
@Configuration
public class AppConfig{
}
(1)配置Bean在应用的过程中替换了XML具体什么内容呢
(2)AnnotationConfigApplicationContext
①.创建工厂
ApplicationContext ctx = new AnnotationConfigApplicationContext();
②。指定配置文件
Ⅰ.指定配置bena的class
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig。class);
Ⅱ.指定配置bean所在的路径
ApplicationContext ctx new AnnotationConfigApplicationContext("com.xxx");
- 配置bean开发的细节分析
- 基于注解开发使用日志
不能集成Log4j
集成logback
(1)引入相关jar
<!--logback相关依赖jar-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.logback-extensions</groupId>
<artifactId>logback-ext-spring</artifactId>
<version>0.1.4</version>
</dependency>
(2)引入logback配置文件(logback.xml)
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- <pattern>%date %5level [%10thread] %logger{20}:%msg%n</pattern>-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -%msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>
- @Configuration注解的本质
本质:也是@Component注解的衍生注解
可以应用<context:component-scan进行扫描
2.@Bean注解
@Bean注解在配置bean中进行使用,等同于XML配置文件中的<bean标签
(1)@Bean注解的基本使用
- 对象的创建
1.简单对象
直接能够通过new的方式创建的对象
User UserService UserDAO
2.复杂对象
不能通过new的方式直接创建的对象
Connection SqlSessionFactory
- @Bean注解创建复杂对象的注意事项
遗留系统整合
@Bean
public Connection conn(){
Connection connection = null;
try {
ConnectionFactoryBean connectionFactoryBean = new ConnectionFactoryBean();
connection = connectionFactoryBean.getObject();
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
- 自定义id值
@Bean("id")
- 控制对象创建次数
@Bean
@Scope("singleton|prototype") 默认值 singleton
(2)@Bean注解的注入
- 用户自定义类型的注入
@Bean
public UserDAO userDAO(){
UserDAOImpl userDAO = new UserDAOImpl();
return userDAO;
}
@Bean
public UserService userService(UserDAO userDAO){
UserServiceImpl userService = new UserServiceImpl();
userService.setUserDAO(userDAO);
return userService;
}
——————————————————————————————————————————————————————————————————————————————
//简化写法
@Bean
public UserService userService(){
UserServiceImpl userService = new UserServiceImpl();
userService.setUserDAO(userDAO());
return userService;
}
- JDK类型的注入
@Bean
public User user(){
User user = new User();
user.setId(1);
user.setName("bugz");
return user;
}
- JDK类型注入的细节分析
如果直接在代码中进行set方法的调用,会存在耦合的问题
@Configuration
@PropertySource("classpath:/init.properties")
public class AppConfig {
@Value("${id}")
private Integer id ;
@Value("${name}")
private String name;
@Bean
public User user(){
User user = new User();
user.setId(id);
user.setName(name);
return user;
}
}
3、@ComponentScan注解
@ComponentScan注解在配置bean中进行使用,等同于XML配置文件中的context:component-scan标签
目的:进行相关注解的扫描(@Component @Value …@Autowired)
(1)基本使用
@Configuration
@ComponentScan(basePackages = "com.spring")
public class AppConfig {}
<context:component-scan base-package=""/>
(2)排除、包含的使用
- 排除
- 包含
4Spring工厂创建对象的多种配置方式
(1).多种配置的应用场景
(2).配置优先级
@Component及其衍生注解 < @Bean < 配置文件及标签
优先级高的配置覆盖优先级低的配置
@Component
public class User{}
@Bean
public User user(){
User user=new User()
return user;
}
<bean id = ”user“ class=”xxx.User“/>
配置覆盖: id 保持一致
@ImportResource("applicationContext.xml")使用配置类时可以用这个标签配合配置文件一起使用
- 解决基于注解配置的耦合问题
@Configuration
//@ImportResource("applicationContext.xml")
public class AppConfig2 {
@Bean
public UserDAO userDAO(){
return new UserDAOImpl();
}
}
@Configuration
@ImportResource("applicationContext.xml")
public class AppConfig3 {
}
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig2.class,AppConfig3.class);
ApplicationContext ctx = new AnnotationConfigApplicationContext("com.xxx.配置类所在包");
applicationContext.xml
<bean id="userDAO" class="com.xxx.xxx.UserDAOImplNew"/>
5.整合多个配置信息
- 为什么会有多个配置信息
拆分多个配置Bean的开发,是一种模块化开发的形式,也体现了面向对象各司其职的设计思想。
- 多种配置信息整合的方式
- 多个配置Bean的整合
- 配置bean与@Component相关注解的整合
- 配置bean与SpringXML配置文件的整合
- 整合多种配置需要关注那些要点
- 如何使多配置的信息汇总成一个整体
- 如何实现跨配置的注入
(1)多个配置bean的整合
- 多配置的信息汇总
- base-package进行多个配置Bean的整合
- @Import
1,可以创建对象
2.多配置bean的整合
- 在工厂创建时,指定多个配置Bean的Class对象
- base-package进行多个配置Bean的整合
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig2.class,AppConfig3.class);
- 跨配置注入
在应用配置Bean的过程中,不管使用哪种方式进行配置信息的汇总,其操作方式都是通过成员变量加入@Autowired注解完成的。
@Autowried
private UserDAO userDAO;
(2)配置Bean与@Component相关注解的整合
(3)配置Bean与配置文件整合
1.整合遗留系统 2.配置覆盖
6.配置Bean底层实现原理
Spring在配置Bean中加入了@Configuration注解后,底层通过Cglib的代理方式,来进行对象相关的配置、处理
7.四维一体的开发思想
(1)什么是思维一体
Spring开发一个功能的4种形式,虽然开发方式不同,但是最终效果是一样的。
①、基于schema
②、基于特定功能注解
③、基于原始<beam>
④、基于@Bean注解
(2)四维一体开发案例
8.纯注解版AOP编程
(1)搭建环境
1.应用配置Bean
2.注解扫描
(2)开发步骤
(3)注解AOP细节分析
9.纯注解版Spring+Mybatis整合
- 基础配置(Bean)
1.连接池
2.SqlSessionFactoryBean
3.MapperScannerConfigure
- 编码
1.实体
2.表
3.DAO接口
4.Mapper文件
Ⅰ.MapperLocations 编码时通配的写法
Ⅱ.配置Bean数据耦合问题
使用配置文件替换配置bean中的字符串信息
10.纯注解版事务编程
11.Spring框架中YML使用
(1)什么是YML”
YML(YAML)是一种新形式的配置文件,比XML更简单,比properties更强大
(2)Properties进行配置问题
1.Properties表达过于繁琐,无法表达数据的内在联系
2.Properties无法表达对象集合类型
(3)YML语法简介
1.定义yml文件
xxx.yml/xxx.yaml
2.语法
①、基本语法
name: bugz
password: 12345
②、对象概念
user:
id: 1
name: bugz
③、定义集合
service:
- 1111
- 2222
(4)Spring与YML集成思路的分析
(5)Spring与YML集成编码
- 环境搭建
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.23</version>
</dependency>
最低版本1.18
- 编码
1.准备yml配置文件
user:
id: 1234
name1: bugz
2.配置Bean 中操作完成YAML读取与PropertySourcePlaceholderConfigure的创建
@Configuration
@ComponentScan(basePackages = "com.spring.yml")
public class YmlConfiguration {
@Bean
public PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
yamlPropertiesFactoryBean.setResources(new ClassPathResource("init1.yaml"));
Properties object = yamlPropertiesFactoryBean.getObject();
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setProperties(object);
return configurer;
}
}
3.类加入@Value注解
@Component
public class User {
@Value("${user.id}")
private Integer id;
@Value("${user.name1}")
private String name;
(6)Spring与YML集成的问题