什么是注解:注解是代码的特殊标记 格式:@注解名称(属性名称=属性值,属性名称=属性值)
注解可以作用在类上面、方法上面、属性上面
使用注解的目的:简化XML配置
1、Spring 针对Bean管理提供的注解
@Component | 对象创建 | 该四种注解本质上并没有区别 可以交替使用 目的是为了区分不同对象 |
@Service | 用于业务层的bean对象创建 | |
@Controller | 用于表现层的bean对象创建 | |
@Repository | 用于数据层的bean对象创建 | |
@Value | 注入属性值 | 通常不会出入字符串 通常会结合properties文件使用 |
@Configuration | 声明该类为spring配置类 | |
@ComponentScan({“com.itheima.service”,“com.itheima.dao”}) | 设置扫描路径 | |
@Scope | 设置bean的作用范围 | //singleton 单实例对象(运行两次都是同一个对象) //prototype 多实例对象 |
设置bean的初始化方法 | ||
@PreDestroy | 设置bean的销毁方法 | |
@Autowired | 自动装配 | byName byType |
@Import | 导入其他配置类信息 | |
@Alias | 设置bean别名 | |
@RunWith | 就是一个运行器 后面加什么反射就是使用什么环境来运行 | 常用用于Junit测试类 @RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境 |
2、基于注解完成对象创建步骤
方式1 xml +注解
1、添加配置文件 指定注解扫描的位置(注意在这里的命名空间多了两行)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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="com.itheima"/>
</beans>
2、使用注解 @Component在方法名上 并设置bean的id 并在测试类中取出该对象
方式2 纯注解
1、开启注解扫描 相当于方式一的第一步骤
@Configuration //声明当前类为Spring配置类
//设置bean扫描路径,多个路径书写为字符串数组格式等价于<context:component-scan base-package=“com.itheima”/>
@ComponentScan({“com.itheima.service”,“com.itheima.dao”})
2、获取bean
3、bean的作用范围和生命周期管理
@Scope设置bean的作用范围
//singleton 单实例对象(运行两次都是同一个对象)
//prototype 多实例对象
@PostConstruct设置bean的初始化方法
@PreDestroy设置bean的销毁方法
package com.itheima.dao.impl;
import com.itheima.dao.BookDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Repository
//@Scope设置bean的作用范围
//singleton 单实例对象(运行两次都是同一个对象)
// prototype 多实例对象
@Scope("singleton")
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("book dao save ...");
}
//@PostConstruct设置bean的初始化方法
@PostConstruct
public void init() {
System.out.println("init ...");
}
//@PreDestroy设置bean的销毁方法
@PreDestroy
public void destroy() {
System.out.println("destroy ...");
}
}
4、@Value如何使用el表达式取properties文件里面的值
编写jdbc.properties文件 需要放在resourse目录下面
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydatabase
username=root
password=7894561230
配置属性源(在spring配置类中).
el表达式注入(备注:name的值是从 jdbcproperties中获取的)
5、注解开发管理第三方Bean例如jdbc dataSourse
主要是为了管理第三方的bean 或者其他框架
创建一个jdbcConfig类(不直接写在SpringConfig类中是为了区分管理)
在SpringConfig配置类中 导入刚刚写好的jdbcConfig配置类 使用@import
@Configuration //声明当前类为Spring配置类
@ComponentScan//开启注解扫描的路径
@Import:导入配置类的信息