Spring(依赖注入)

1.Bean的作用域
bean的作用域:主要是指Spring创建的Bean对象是单例、多例、request、session级别。
在这里插入图片描述

singleton: 单例模式【在一个spring容器中,对象只有一个实例。(默认值)】
prototype:多例模式/原型模式【在一个spring容器中,存在多个实例,每次getBean 返回一个新的实例。】

request:该属性仅对HTTP请求产生作用,使用该属性定义Bean时,每次HTTP请求都会创建一个新的Bean,适用于WebApplicationContext环境。【一次请求一个对象】
session:该属性仅用于HTTP Session,同一个Session共享一个Bean实例。不同Session使用不同的实例。【同一次回话中的对象都是相同的】
global session:该属性仅用于HTTP Session,同session作用域不同的是,所有的Session共享一个Bean实例。【多个session共享一个对象】
下面重点讨论singleton、prototyp作用域,request,session和global-session类作用域放到Spring MVC章节讨论,这里不再做详细讲述。
通过在配置Spring配置文件是设置bean元素的scope属性设置bean的作用域
package com.wangxing.sping.bean;
public class Student {
public void getInfo(){
System.out.println(“Student的实例方法”);
}
}
测试单例作用域 singleton

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
     <!-- 测试单例作用域 singleton 【默认值】 -->
    <!--在一个spring容器中,对象只有一个实例。-->
    <bean id="stu" class="com.wangxing.sping.bean.Student" scope="singleton"></bean>
</beans>

测试原型作用域 prototype

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
<!-- 测试原型作用域 prototype -->
    <!--在一个spring容器中,存在多个实例,每次getBean 返回一个新的实例-->
    <bean id="stu" class="com.wangxing.sping.bean.Student" scope="prototype"></bean>
</beans>

package com.wangxing.sping.test;
import com.wangxing.sping.bean.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestMain {
    public static void main(String[] args) {
        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml");
        Student student1=(Student)ac.getBean("stu");
        Student student2=(Student)ac.getBean("stu");
        System.out.println("student1--"+student1.hashCode());
        System.out.println("student2--"+student2.hashCode());
    }
}

2.Bean的生命周期
Spring工厂对象【Spring容器对象】负责创建对象,初始化对象,销毁对象。
也就是说任何一个交给Spring的Bean,它的生命周期统一由Spring容器维护。
1.创建对象[参考bean实例化的4中方式]
2.初始化

package com.wangxing.sping.bean;
public class Student {
    public  void  getInfo(){
        System.out.println("Student的实例方法");
    }
    public  void  initstudent(){
        System.out.println("Student的初始化方法");
    }
}


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
    <!--通过设置init-method属性设置初始化方法的执行-->
    <bean id="stu" class="com.wangxing.sping.bean.Student" init-method="initstudent"></bean>
</beans>

3.销毁对象
Bean的销毁必须满足两个条件:
1、bean必须是单例的。
2.bean的所在的容器(Spring)必须手动关闭

package com.wangxing.sping.bean;
public class Student {
    public  void  getInfo(){
        System.out.println("Student的实例方法");
    }
    public  void  destroyStudent(){
        System.out.println("Student类对象的销毁");
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
    <!--通过设置destroy-method属性设置销毁方法的执行-->
<bean id="stu" class="com.wangxing.sping.bean.Student" scope="singleton" destroy-method="destroyStudent"></bean>
</beans>

ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml");
Student student1=(Student)ac.getBean("stu");
//关闭spring容器对象
((ClassPathXmlApplicationContext)ac).close();

3.Spring的依赖注入是什么,实现方式有几种,每一种如何操作?
DI–依赖注入,建立在IoC[控制反转]基础之上的,没有控制反转就谈不上依赖注入。
解释依赖注入的话,需要先引入两个概念,第一个就是调用者类,第二个就是被调用者类。
例如:

Public  class  SelectServlet extends HttpServlet{
//定义一个数据访问接口对象
Private  StudentMapper  studentMapper=null;

Public  void  doGet(){
doPost();
}

Public void  doPost(HttpServletRequest req,HttpServletResponse resp ){
    //调用数据库访问接口中的查询方法
//实例化定义的数据访问接口
studentMapper=new StudentMapperImpl();
//调用查询方法
List<StudentBean> studentlist=studentMapper.selectStudent();
    Req.getSession.setAttrxxxx(xxx,xxxx);
Resp.sendxxxx(“main.jsp”); 
}
}

在上面的例子中SelectServlet 就是调用者类,它需要StudentMapper数据访问接口对象,此时StudentMapper数据访问接口对象就是被调用者类。
依赖注入–在调用者类[SelectServlet ]中将被调用者类[StudentMapper]的对象,添加到调用者类中这个过程就是依赖注入。
在这个过程中被调用者类的对象就是调用者类的依赖对象。
实现依赖注入的方式
1.基于XML注入Bean
1.构造方法注入【通过构造方法传递参数的形式】

package com.wangxing.spring.bean;
//被调用者类
public class Student {
    public void  stuInfo(){
        System.out.println("被调用者类Student的实例方法");
    }
}

package com.wangxing.spring.bean;
//调用者类
public class StudentService {
    //定义被调用者类的对象
    private  Student student;
    //创建调用者类的构造方法,让被调用者类的对象作为参数
    public  StudentService(Student student) {
        this.student = student;
    }
    public  void studentMethod(){
        //使用注入进来的被调用者类的对象
        student.stuInfo();
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
       <!--配置构造方法注入-->
       <!--1.创建被调用者类对象  -->
       <bean id="stu" class="com.wangxing.spring.bean.Student"></bean>
       <!--2.用过构造方法将上面创建的被调用者类对象注入到调用者类中-->
       <bean id="stuservice" class="com.wangxing.spring.bean.StudentService">
           <!--constructor-arg构造方法注入元素-->
           <!-- index="0":构造方法参数的索引值-->
           <!-- ref="stu":指定被注入的具体数据值-->
           <constructor-arg index="0" ref="stu"></constructor-arg>
       </bean>
</beans>

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
StudentService studentService=(StudentService)applicationContext.getBean("stuservice");
studentService.studentMethod();

2.Set方法注入【通过依赖对象的Set方法】【常用】

package com.wangxing.spring.bean;
//被调用者类
public class Person {
    public void perinfo(){
        System.out.println("被调用者类Person的实例方法");
    }
}

package com.wangxing.spring.bean;
//调用者类
public class PersonService {
    //定义依赖对象
    private  Person person;
    //为依赖对象提供Set方法
    public void setPerson(Person person) {
        this.person = person;
    }
    public void  personMethod() {
        //使用注入成功的依赖对象
        person.perinfo();
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
       <!--配置Set方法注入-->
       <!--1.创建被调用者类对象  -->
       <bean id="per" class="com.wangxing.spring.bean.Person"></bean>
       <!--2.用过set方法将上面创建的被调用者类对象注入到调用者类中-->
       <bean id="perservice" class="com.wangxing.spring.bean.PersonService">
           <!--property:set方法注入需要使用的元素-->
           <!--name="person":调用者类中定义的依赖对象的名称-->
           <!--ref="per":指定被注入的具体数据值-->
           <property name="person" ref="per"></property>
       </bean>
</beans>

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
PersonService personService=(PersonService)applicationContext.getBean("perservice");
personService.personMethod();

通过Set方法注入
【基本类型数据,String,时间日期,数组【对象】,List集合【对象】,Set集合【对象】,Map集合【值-对象】,Properties】

package com.wangxing.spring.helper;

import java.util.*;

public class Helper {
    //基本类型数据
    private  int intvalue;
    private  double doublevalue;
    private  char charvalue;
    private  boolean booleanvalue;
    //String
    private  String stringvalue;
    //时间日期
    private Date datevalue;
    //pojo
    private Student studentvalue;
    //数组
    private String stringArrayvalue[];
    private Student studentArrayvalue[];
    //List
    private List<String> stringListvalue;
    private List<Student> studentListvalue;
    //Set
    private Set<String> stringSetvalue;
    private Set<Student> studentSetvalue;
    //Map
    private Map<String,String> stringMapvalue;
    private Map<String,Student> studentMapvalue;
    //Properties
    private Properties propertiesvalue;

    public int getIntvalue() {
        return intvalue;
    }

    public void setIntvalue(int intvalue) {
        this.intvalue = intvalue;
    }

    public double getDoublevalue() {
        return doublevalue;
    }

    public void setDoublevalue(double doublevalue) {
        this.doublevalue = doublevalue;
    }

    public char getCharvalue() {
        return charvalue;
    }

    public void setCharvalue(char charvalue) {
        this.charvalue = charvalue;
    }

    public boolean isBooleanvalue() {
        return booleanvalue;
    }

    public void setBooleanvalue(boolean booleanvalue) {
        this.booleanvalue = booleanvalue;
    }

    public String getStringvalue() {
        return stringvalue;
    }

    public void setStringvalue(String stringvalue) {
        this.stringvalue = stringvalue;
    }

    public Date getDatevalue() {
        return datevalue;
    }

    public void setDatevalue(Date datevalue) {
        this.datevalue = datevalue;
    }

    public Student getStudentvalue() {
        return studentvalue;
    }

    public void setStudentvalue(Student studentvalue) {
        this.studentvalue = studentvalue;
    }

    public String[] getStringArrayvalue() {
        return stringArrayvalue;
    }

    public void setStringArrayvalue(String[] stringArrayvalue) {
        this.stringArrayvalue = stringArrayvalue;
    }

    public Student[] getStudentArrayvalue() {
        return studentArrayvalue;
    }

    public void setStudentArrayvalue(Student[] studentArrayvalue) {
        this.studentArrayvalue = studentArrayvalue;
    }

    public List<String> getStringListvalue() {
        return stringListvalue;
    }

    public void setStringListvalue(List<String> stringListvalue) {
        this.stringListvalue = stringListvalue;
    }

    public List<Student> getStudentListvalue() {
        return studentListvalue;
    }

    public void setStudentListvalue(List<Student> studentListvalue) {
        this.studentListvalue = studentListvalue;
    }

    public Set<String> getStringSetvalue() {
        return stringSetvalue;
    }

    public void setStringSetvalue(Set<String> stringSetvalue) {
        this.stringSetvalue = stringSetvalue;
    }

    public Set<Student> getStudentSetvalue() {
        return studentSetvalue;
    }

    public void setStudentSetvalue(Set<Student> studentSetvalue) {
        this.studentSetvalue = studentSetvalue;
    }

    public Map<String, String> getStringMapvalue() {
        return stringMapvalue;
    }

    public void setStringMapvalue(Map<String, String> stringMapvalue) {
        this.stringMapvalue = stringMapvalue;
    }

    public Map<String, Student> getStudentMapvalue() {
        return studentMapvalue;
    }

    public void setStudentMapvalue(Map<String, Student> studentMapvalue) {
        this.studentMapvalue = studentMapvalue;
    }

    public Properties getPropertiesvalue() {
        return propertiesvalue;
    }

    public void setPropertiesvalue(Properties propertiesvalue) {
        this.propertiesvalue = propertiesvalue;
    }
}


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
    <!-- 通过Set方法注入
     【基本类型数据,String,时间日期,数组【对象】,List集合【对象】,Set集合【对象】,Map集合【值-对象】,Properties】 -->
    <bean id="student1" class="com.wangxing.spring.helper.Student"></bean>
    <bean id="student2" class="com.wangxing.spring.helper.Student"></bean>
    <bean id="student3" class="com.wangxing.spring.helper.Student"></bean>
    <bean id="student4" class="com.wangxing.spring.helper.Student"></bean>
    <!--创建SimpleDateFormat-->
    <bean id="simpleDateFormat" class="java.text.SimpleDateFormat">
        <constructor-arg index="0" value="yyyy-MM-dd"></constructor-arg>
    </bean>
    <bean id="helper" class="com.wangxing.spring.helper.Helper">
        <!-- 基本类型数据-->
        <property name="intvalue" value="1001"></property>
        <property name="doublevalue" value="168.5"></property>
        <property name="charvalue" value="A"></property>
        <property name="booleanvalue" value="true"></property>
        <!-- String-->
        <property name="stringvalue" value="zhangsan"></property>
        <!--pojo-->
        <property name="studentvalue" ref="student1"></property>
        <!--时间日期-->
        <property name="datevalue" >
            <bean  factory-bean="simpleDateFormat" factory-method="parse">
                <constructor-arg value="2020-11-18"></constructor-arg>
            </bean>
        </property>
        <!--数组 String-->
        <property name="stringArrayvalue">
            <array>
                <value>zhangsan</value>
                <value>lisi</value>
                <value>wangwu</value>
                <value>zhaoliu</value>
            </array>
        </property>
        <!--数组 Student-->
        <property name="studentArrayvalue">
            <array>
                <ref bean="student1"></ref>
                <ref bean="student2"></ref>
                <ref bean="student3"></ref>
                <ref bean="student4"></ref>
            </array>
        </property>
        <!--List string-->
        <property name="stringListvalue">
            <list>
                <value>zhangsan</value>
                <value>lisi</value>
                <value>wangwu</value>
                <value>zhaoliu</value>
            </list>
        </property>
        <!--List Student-->
        <property name="studentListvalue">
            <list>
                <ref bean="student1"></ref>
                <ref bean="student2"></ref>
                <ref bean="student3"></ref>
                <ref bean="student4"></ref>
            </list>
        </property>
        <!--Set String-->
        <property name="stringSetvalue">
            <set>
                <value>zhangsan</value>
                <value>lisi</value>
                <value>wangwu</value>
                <value>zhaoliu</value>
            </set>
        </property>
        <!--Set Student-->
        <property name="studentSetvalue">
            <set>
                <ref bean="student1"></ref>
                <ref bean="student2"></ref>
                <ref bean="student3"></ref>
                <ref bean="student4"></ref>
            </set>
        </property>
        <!--Map String-->
        <property name="stringMapvalue">
            <map>
               <entry key="name" value="zhangsan"></entry>
               <entry key="age" value="23"></entry>
               <entry key="address">
                   <value>西安</value>
               </entry>
            </map>
        </property>
        <!--Map Student-->
        <property name="studentMapvalue">
            <map>
                <entry key="stu1" value-ref="student1"></entry>
                <entry key="stu2" value-ref="student2"></entry>
                <entry key="stu3" value-ref="student3"></entry>
                <entry key="stu4" value-ref="student4"></entry>
            </map>
        </property>
        <!-- properties  -->
        <property name="propertiesvalue">
            <props>
                <prop key="mydriver" >com.jdbc.mydql.Driver</prop>
                <prop key="myurl" >jdbc:mysql://127.0.0.1:3306/test</prop>
                <prop key="myname" >root</prop>
                <prop key="mypassword" >123456</prop>
            </props>
        </property>
    </bean>
</beans>
测试代码
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
Helper helper=(Helper)applicationContext.getBean("helper");
System.out.println("int--"+helper.getIntvalue());
System.out.println("bouble--"+helper.getDoublevalue());
System.out.println("char--"+helper.getCharvalue());
System.out.println("boolean--"+helper.isBooleanvalue());
System.out.println("String--"+helper.getStringvalue());
helper.getStudentvalue().stuInfo();
System.out.println("Date--"+helper.getDatevalue());
String strArray[]=helper.getStringArrayvalue();
for(String str:strArray){
    System.out.println("strArray=="+str);
}
Student studentArray[]=helper.getStudentArrayvalue();
for(Student stu:studentArray){
    System.out.println("studentArray=="+stu.hashCode());
}
List<String> stringList=helper.getStringListvalue();
for(String str:stringList){
    System.out.println("stringList=="+str);
}
List<Student> studentList=helper.getStudentListvalue();
for(Student stu:studentList){
    System.out.println("studentList=="+stu.hashCode());
}
Set<String> stringSet=helper.getStringSetvalue();
for(String str:stringSet){
    System.out.println("stringSet=="+str);
}
Set<Student> studentSet=helper.getStudentSetvalue();
for(Student stu:studentSet){
    System.out.println("studentSet=="+stu.hashCode());
}
Map<String,String> stringMap=helper.getStringMapvalue();
for(Map.Entry<String,String> entry:stringMap.entrySet()){
    System.out.println(entry.getKey()+"=="+entry.getValue());
}
Map<String,Student> studentMap=helper.getStudentMapvalue();
for(Map.Entry<String,Student> entry:studentMap.entrySet()){
    System.out.println(entry.getKey()+"=="+entry.getValue().hashCode());
}
Properties properties=helper.getPropertiesvalue();
//properties.stringPropertyNames()得到所有的key值封装到Set集合
Iterator<String> propkeys=properties.stringPropertyNames().iterator();
while(propkeys.hasNext()){
    String keyvalue=propkeys.next();
    String myvalue=properties.getProperty(keyvalue);
    System.out.println("Properties=="+keyvalue+"-"+myvalue);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值