易语言怎么做点击按钮打开网站,wordpress下安装论坛 伪静态,安徽省交通运输厅领导,自动制作视频的软件SpringDI 什么是依赖注入 依赖注入#xff08;Dependency Injection#xff0c;简称DI#xff09;#xff0c;它是Spring控制反转思想的具体实现。
控制反转将对象的创建交给了Spring#xff0c;但是对象中可能会依赖其他对象。比如service类中要有dao类的属性#xff0…SpringDI 什么是依赖注入 依赖注入Dependency Injection简称DI它是Spring控制反转思想的具体实现。
控制反转将对象的创建交给了Spring但是对象中可能会依赖其他对象。比如service类中要有dao类的属性我们称service依赖于dao。之前需要手动注入属性值代码如下
public interface StudentDao {Student findById(int id);
}public class StudentDaoImpl implements StudentDao{Overridepublic Student findById(int id) {// 模拟根据id查询学生return new Student(1,张三,北京);}
}public class StudentService {// service依赖dao手动注入属性值即手动维护依赖关系private StudentDao studentDao new StudentDaoImpl();public Student findStudentById(int id){return studentDao.findById(id);}
}此时当StudentService的想要使用StudentDao的另一个实现类如StudentDaoImpl2时则需要修改Java源码造成代码的可维护性降低。
而使用Spring框架后Spring管理Service对象与Dao对象此时它能够为Service对象注入依赖的Dao属性值。这就是Spring的依赖注入。简单来说控制反转是创建对象依赖注入是为对象的属性赋值。
依赖注入方式 在之前开发中可以通过setter方法或构造方法设置对象属性值
// setter方法设置属性
StudentService studentService new StudentService();
StudentDao studentDao new StudentDao();
studentService.setStudentDao(studentDao);// 构造方法设置属性
StudentDao studentDao new StudentDao();
StudentService studentService new StudentService(studentDao);Spring可以通过调用setter方法或构造方法给属性赋值
Setter注入 被注入类编写属性的setter方法 public class StudentService {private StudentDao studentDao;public void setStudentDao(StudentDao studentDao) {this.studentDao studentDao;}
}配置文件中给需要注入属性值的bean中设置property bean idstudentDao classcom.Spring.dao.StudentDaoImpl/bean
bean idstudentService classcom.Spring.service.StudentService!--依赖注入--!--name:对象的属性名 ref:容器中对象的id值--property namestudentDao refstudentDao/property
/bean测试是否注入成功 Test
public void t2(){ApplicationContext ac new ClassPathXmlApplicationContext(bean.xml);StudentService studentService (StudentService) ac.getBean(studentService);System.out.println(studentService.findStudentById(1));
}构造方法注入 被注入类编写有参的构造方法 public class StudentService {private StudentDao studentDao;public StudentService(StudentDao studentDao) {this.studentDao studentDao;}
}给需要注入属性值的bean中设置constructor-arg bean idstudentDao classcom.Spring.dao.StudentDaoImpl/beanbean idstudentService classcom.Spring.service.StudentService!-- 依赖注入 --!-- name:对象的属性名 ref配置文件中注入对象的id值 --constructor-arg namestudentDao refstudentDao/constructor-arg
/bean测试是否注入成功 Test
public void t2(){ApplicationContext ac new ClassPathXmlApplicationContext(bean.xml);StudentService studentService (StudentService) ac.getBean(studentService);System.out.println(studentService.findStudentById(1));
}自动注入
自动注入不需要在bean标签中添加其他标签注入属性值而是自动从容器中找到相应的bean对象设置为属性值。 自动注入有两种配置方式 全局配置在beans中设置default-autowire属性可以定义所有bean对象的自动注入策略。局部配置在bean中设置autowire属性可以定义当前bean对象的自动注入策略。 autowire的取值如下 no不会进行自动注入。default全局配置default相当于no局部配置default表示使用全局配置byName在Spring容器中查找id与属性名相同的bean并进行注入。需要提供set方法。byType在Spring容器中查找类型与属性类型相同的bean并进行注入。需要提供set方法。constructor在Spring容器中查找id与属性名相同的bean并进行注入。需要提供构造方法。 测试自动注入 为依赖的对象提供setter和构造方法 public class StudentService {// 依赖private StudentDao studentDao;// 构造方法public StudentService() {}public StudentService(StudentDao studentDao) {this.studentDao studentDao;}// setter方法public void setStudentDao(StudentDao studentDao) {this.studentDao studentDao;}// 调用依赖的方法public Student findStudentById(int id) {return studentDao.findById(id);}
} 配置自动注入 !-- 根据beanId等于属性名自动注入 --
bean idstudentDao classcom.Spring.dao.StudentDaoImpl/bean
bean idstudentService classcom.Spring.service.StudentService autowirebyName/bean !-- 根据bean类型等于属性类型自动注入 --
bean idstudentDao classcom.Spring.dao.StudentDaoImpl/bean
bean idstudentService classcom.Spring.service.StudentService autowirebyType/bean !-- 利用构造方法自动注入 --
bean idstudentDao classcom.Spring.dao.StudentDaoImpl/bean
bean idstudentService classcom.Spring.service.StudentService autowireconstructor/bean!-- 配置全局自动注入 --
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsddefault-autowireconstructor
依赖注入类型
DI支持注入bean类型、基本数据类型和字符串、List集合、Set集合、Map集合、Properties对象类型等他们的写法如下 准备注入属性的类 public class StudentService {private StudentDao studentDao; // bean属性private String name; //字符串类型private int count; //基本数据类型private ListString names; // 字符串类型List集合private ListStudent students1; // 对象类型List集合private SetStudent students2; // 对象类型Set集合private MapString,String names2; // 字符串类型Map集合private MapString,Student students3; // 对象类型Map集合private Properties properties; //Properties类型// 省略getter/setter/toString
} 准备测试方法 Test
public void t3(){ApplicationContext ac new ClassPathXmlApplicationContext(bean.xml);StudentService studentService (StudentService) ac.getBean(studentService);System.out.println(studentService);
}
注入bean类型
写法一
bean idstudentDao classcom.Spring.dao.StudentDaoImpl/beanbean idstudentService classcom.Spring.service.StudentServiceproperty namestudentDao refstudentDao/property
/bean
写法二
bean idstudentDao classcom.Spring.dao.StudentDaoImpl/beanbean idstudentService classcom.Spring.service.StudentServiceproperty namestudentDao ref beanstudentDao/ref/property
/bean
注入基本数据类型和字符串类型
bean idstudentService classcom.Spring.service.StudentService!-- 写法一 name属性名 value属性值--property namename value李四/property!-- 写法二 name属性名 value属性值--property namecountvalue10/value/property
/bean
注入List集合
bean idstudentService classcom.Spring.service.StudentService!-- 简单数据类型List集合 name属性名 --property namenameslistvalueSpring/valuevalue张三/value/list/property!-- 对象类型List集合 name属性名 --property namestudents1listbean classcom.Spring.domain.Studentproperty nameid value1/property namename valueSpring/property nameaddress value北京//beanbean classcom.Spring.domain.Studentproperty nameid value2/property namename value李四/property nameaddress value北京//bean/list/property
/bean
注入Set集合
bean idstudentService classcom.Spring.service.StudentService!-- Set集合 --property namestudents2setbean classcom.Spring.domain.Studentproperty nameid value1/property namename valueSpring/property nameaddress value北京//beanbean classcom.Spring.domain.Studentproperty nameid value2/property namename value李四/property nameaddress value北京//bean/set/property
/bean
注入Map集合
简单数据类型Map集合
bean idstudentService classcom.Spring.service.StudentServiceproperty namenames2mapentry keystudent1 value李四/entry keystudent2 value张三//map/property
/bean
对象类型Map集合
bean idstudentService classcom.Spring.service.StudentServiceproperty namestudents3mapentry keystudent1 value-refs1/entry keystudent2 value-refs2//map/property
/beanbean ids1 classcom.Spring.domain.Studentproperty nameid value1/property namename valueSpring/property nameaddress value北京/
/bean
bean ids2 classcom.Spring.domain.Studentproperty nameid value2/property namename value李四/property nameaddress value北京/
/bean
注入Properties对象
bean idstudentService classcom.Spring.service.StudentServiceproperty namepropertiespropsprop key配置1值1/propprop key配置2值2/prop/props/property
/bean注解实现IOC
准备工作
注解配置和xml配置对于Spring的IOC要实现的功能都是一样的只是配置的形式不一样。
准备工作 创建一个新的Spring项目。 编写pojodaoservice类。 编写空的配置文件如果想让该文件支持注解需要添加新的约束 ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:contexthttp://www.springframework.org/schema/contextxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd/beans
Component
作用用于创建对象放入Spring容器相当于bean id class
位置类上方
注意 要在配置文件中配置扫描的包扫描到该注解才能生效。 context:component-scan base-packagecom.Spring/context:component-scanComponent注解配置bean的默认id是首字母小写的类名。也可以手动设置bean的id值。 // 此时bean的id为studentDaoImpl
Component
public class StudentDaoImpl implements StudentDao{public Student findById(int id) {// 模拟根据id查询学生return new Student(1,张三,北京);}
}// 此时bean的id为studentDao Component(“studentDao”) public class StudentDaoImpl implements StudentDao{ public Student findById(int id) { // 模拟根据id查询学生 return new Student(1,“张三”,“北京”); } } Repository、Service、Controller
作用这三个注解和Component的作用一样使用它们是为了区分该类属于什么层。
位置
Repository用于Dao层Service用于Service层Controller用于Controller层
Repository
public class StudentDaoImpl implements StudentDao{}Service
public class StudentService {}Scope
作用指定bean的创建策略
位置类上方
取值singleton prototype request session globalsession
Service
Scope(singleton)
public class StudentService {}Autowired
作用从容器中查找符合属性类型的对象自动注入属性中。用于代替bean中的依赖注入配置。
位置属性上方、setter方法上方、构造方法上方。
注意 Autowired写在属性上方进行依赖注入时可以省略setter方法。 Component
public class StudentService {Autowiredprivate StudentDao studentDao;public Student findStudentById(int id){return studentDao.findById(id);}
}Test
public void t2(){ApplicationContext ac new ClassPathXmlApplicationContext(bean.xml);StudentService studentService (StudentService) ac.getBean(studentService);System.out.println(studentService.findStudentById(1));
}容器中没有对应类型的对象会报错 // 如果StudentDaoImpl没有放到容器中会报错
//Component(studentDao)
public class StudentDaoImpl implements StudentDao{public Student findById(int id) {// 模拟根据id查询学生return new Student(1,张三,北京);}
}容器中有多个对象匹配类型时会找beanId等于属性名的对象找不到会报错。 // 如果容器中都多个同类型对象会根据id值等于属性名找对象
Component(studentDao)
public class StudentDaoImpl implements StudentDao{public Student findById(int id) {// 模拟根据id查询学生return new Student(1,张三,北京);}
}Component
public class StudentDaoImpl2 implements StudentDao{public Student findById(int id) {// 模拟根据id查询学生return new Student(1,张三,北京);}
}Qualifier
作用在按照类型注入对象的基础上再按照bean的id注入。
位置属性上方
注意Qualifier必须和Autowired一起使用。
Component
public class StudentService {AutowiredQualifier(studentDaoImpl2)private StudentDao studentDao;public Student findStudentById(int id){return studentDao.findById(id);}
}
Value
作用注入String类型和基本数据类型的属性值。
位置属性上方
用法 直接设置固定的属性值 Service
public class StudentService {Value(1)private int count;Value(hello)private String str;
} 获取配置文件中的属性值 编写配置文件db.properties jdbc.usernameroot
jdbc.password123456spring核心配置文件扫描配置文件 context:property-placeholder locationdb.properties/context:property-placeholder注入配置文件中的属性值 Value(${jdbc.username})
private String username;Value(${jdbc.password})
private String password;Configuration
此时基于注解的IOC配置已经完成但是我们依然离不开Spring的xml配置文件。接下来我们脱离bean.xml使用纯注解实现IOC。 在真实开发中我们一般还是会保留xml配置文件很多情况下使用配置文件更加方便。 纯注解实现IOC需要一个Java类代替xml文件。这个Java类上方需要添加Configuration表示该类是一个配置类作用是代替配置文件。
Configuration
public class SpringConfig {
}ComponentScan
作用指定spring在初始化容器时扫描的包。
位置配置类上方
Configuration
ComponentScan(com.Spring)
public class SpringConfig {
}PropertySource
作用代替配置文件中的context:property-placeholder扫描配置文件
位置配置类上方
注意配置文件位置前要加关键字classpath
Configuration
PropertySource(classpath:db.properties)
public class JdbcConfig {Value(${jdbc.username})private String username;Value(${jdbc.password})private String password;}Bean
作用将方法的返回值对象放入Spring容器中。如果想将第三方类的对象放入容器可以使用Bean
位置配置类的方法上方。
属性name给bean对象设置id
注意Bean修饰的方法如果有参数spring会根据参数类型从容器中查找可用对象。
举例如果想将jdbc连接对象放入Spring容器我们无法修改Connection源码添加Component此时就需要使用将Bean该对象放入Spring容器 添加驱动依赖 dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion8.0.27/version
/dependency将Connection对象放入Spring容器 Bean(name connection)
public Connection getConnection(){try {Class.forName(com.mysql.cj.jdbc.Driver);return DriverManager.getConnection(jdbc:mysql:///mysql, root, root);} catch (Exception exception) {return null;}
}测试 Test
public void t5(){ApplicationContext ac new AnnotationConfigApplicationContext(SpringConfig.class);Connection connection (Connection) ac.getBean(connection);System.out.println(connection);
}Import
作用如果配置过多会有多个配置类该注解可以为主配置类导入其他配置类
位置主配置类上方
// Jdbc配置类
Configuration
public class JdbcConfig {Bean(name connection)public Connection getConnection(){try {Class.forName(com.mysql.cj.jdbc.Driver);return DriverManager.getConnection(jdbc:mysql:///mysql, root, root);} catch (Exception exception) {return null;}}
}// 主配置类
Configuration
ComponentScan(com.Spring)
Import(JdbcConfig.class)
public class SpringConfig {
}