Spring依赖注入的三种形式

在2.5版本之前,我们采用xml文件注入的形式

在2.5版本后,采用了annonation+xml的形式

在3.0版本后,采用了annonation+javaConfig配置类的形式

一.以*.xml文件形式注入的三种方法

1.set注入

可注入类型:基本数据类型、String、对象、复杂类型

创建实体类

public class Student {
    //基本数据类型和String
    private String stuname;
    private String stuhobby;
    private int stuage;

    public void setStuname(String stuname) {this.stuname = stuname;}

    public void setStuhobby(String stuhobby) {this.stuhobby = stuhobby;}

    public void setStuage(int stuage) {this.stuage = stuage;}

    @Override
    public String toString() {
        return "Student{" +
                "stuname='" + stuname + '\'' +
                ", stuhobby='" + stuhobby + '\'' +
                ", stuage=" + stuage +
                '}';
    }
}
public class Teacher {
    //复杂类型的五种类型
    private List mylist;
    private Set myset;
    private String[] myarray;
    private Map mymap;
    private Properties prop;

    public void setMylist(List mylist) {this.mylist = mylist;}

    public void setMyset(Set myset) {this.myset = myset;}

    public void setMyarray(String[] myarray) {this.myarray = myarray;}

    public void setMymap(Map mymap) {this.mymap = mymap;}

    public void setProp(Properties prop) {this.prop = prop;}

    @Override
    public String toString() {
        return "Teacher{" +
                "mylist=" + mylist +
                ", myset=" + myset +
                ", myarray=" + Arrays.toString(myarray) +
                ", mymap=" + mymap +
                ", prop=" + prop +
                '}';
    }
}
//创建两个抽象方法以及其实现类
public interface fatherdemo {
    public void say();
}
public class Father implements fatherdemo{
    public Son son;
    
    public void setSon(Son son) {this.son = son;}

    @Override
    public void say() {
        System.out.println("hi,my son");
        son.say();
    }
}


public interface sondemo {
    public void say();
}
public class Son implements sondemo{
    @Override
    public void say() {
        System.out.println("hello,dady");
    }
}

 注入并测试:

<!--===================set注入基本类型与String==========================-->
    <bean id="student" class="com.apesource.pojo.Student">
        <property name="stuname" value="GGBOY"></property>
        <property name="stuhobby" value="唱跳rap"></property>
        <property name="stuage" value="23"></property>
    </bean>
<!--===================测试==========================-->
     public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("*.xml");
        Student student = (Student) applicationContext.getBean("student");
        System.out.println(student);
    }
}
<!--===================set注入复杂类型==========================-->
    <bean id="teacher" class="com.apesource.pojo.Teacher">
        <!--list-->
        <property name="mylist">
            <list>
                <value>密室逃脱</value>
                <value>桌游</value>
                <value>推本</value>
            </list>
        </property>

        <!--set-->
        <property name="myset">
            <set>
                <value>健身</value>
                <value>篮球</value>
            </set>
        </property>

        <!--array-->
        <property name="myarray">
            <array>
                <value>字节跳动</value>
                <value>阿里巴巴</value>
                <value>三星</value>
            </array>
        </property>

        <!--map-->
        <property name="mymap">
            <map>
                <entry key="花和尚" value="鲁智深"></entry>
                <entry key="豹子头" value="林冲"></entry>
            </map>
        </property>

        <!--properties-->
        <property name="prop">
            <props>
                <prop key="凉皮">7</prop>
                <prop key="肉夹馍">10</prop>
            </props>
        </property>
    </bean>

<!--===================测试==========================-->

public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("*.xml");

        Teacher teacher = (Teacher) applicationContext.getBean("teacher");
        System.out.println(teacher);
    }

<!--===================set注入对象==========================-->
    <bean id="father" class="com.my.demo.Father">
        <property name="son" ref="son1"></property>
          <!--实现类set方法--><!--  id      -->
    </bean>

    <bean id="son1" class="com.my.demo.Son"></bean>
<!--===================测试==========================-->
public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("*.xml");
        Father father = (Father) applicationContext.getBean("father");
        father.say();
    }

由测试结果可看到,son类中的对象由Bean创建 

2.构造方法注入

通过构造方法维护对象之间的依赖关系,创建构造方法

//Student类中的有参构造方法 
publiv void Student(String name,int age){
       
       this.stuname = name;
       this.stuage = age;
    
    }
//Father类中创建有参构造方法
public Father(Son son) {this.son = son;}

注入并测试:

   配置属性:
        name======》构造方法参数名称
        index=====》构造方法参数下标
        type======》构造方法参数类型
        value=====》属性值
        ref=======》属性值的引用
    <!--构造注入基本类型与String方式1-->
    <bean id="student1" class="com.apesource.pojo.Student">
        <constructor-arg name="stuname" value="GGBOND"></constructor-arg>
        <constructor-arg name="stuage" value="200"></constructor-arg>
    </bean>

    <!--构造注入基本类型与String方式2-->
    <bean id="student2" class="com.apesource.pojo.Student">
        <constructor-arg index="0" value="迪迦"></constructor-arg>
        <constructor-arg index="1" value="22"></constructor-arg>
    </bean>

    <!--构造注入基本类型与String方式3-->
    <bean id="student3" class="com.apesource.pojo.Student">
        <constructor-arg type="java.lang.String" value="不知名的网友"></constructor-arg>
        <constructor-arg type="int" value="23"></constructor-arg>
    </bean>
<!--===================测试==========================-->
public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("*.xml");
        Student student1 = (Student)applicationContext.getBean("student1");
        Student student2 = (Student)applicationContext.getBean("student2");
        Student student3 = (Student)applicationContext.getBean("student3");
        System.out.println(student1);
        System.out.println(student2);
        System.out.println(student3);
}

     <!--构造注入对象-->
    <bean id="Son" class="com.my.demo.Son"></bean>

    <bean id="father" class="com.my.demo.Father">
        <constructor-arg name="son" ref="Son"></constructor-arg>
    </bean>
<!--===================测试==========================-->
 public static void main(String[] args) {
       ApplicationContext applicationContext = new ClassPathXmlApplicationContext("*.xml");
       fatherdemo fatherdemo = (fatherdemo) applicationContext.getBean("father");
       fatherdemo.say();
    }

3.属性注入(不推荐)

二.以annonnation+xml形式注入依赖

1.注入类

需先在xml文件中加入:

<context:component-scan base-package="com.my"></context:component-scan>
      <!--扫描-->                         <!--所有类的根目录-->
        @Component
            含义:将注解所修饰的类注入spring容器
            位置:类
            语法:@Component(value = "id")
                 如果省略value="id"默认注入的id为类的名称且首字母小写
        @Repository 注入数据访问层
        @Service    注入业务层
        @Controller 注入控制层
        以上三个注解与@Component功能语法一致
        三层之间需要串联调用时,在实例化对象上加@Autowired标签即可

2.注入数据

需先在xml文件中加入:

    <context:property-placeholder location="classpath:msg.properties"></context:property-placeholder>                              
                  <!--加载资源文件-->                           <!--资源文件位置-->
        @Value()
            含义:向属性注入基本类型与String
            语法:@Value("数据"),直接加注载参数上
                 @Value("${key}")直接加注载参数上,key与properties资源文件中的key匹配
            位置:属性
            注意:不能单独使用
        @Autowired()
            替换:自动装配属性
            位置:属性
            语法:在全局中查找所注释的实例化对象的类型
            含义:通过“set”方法【set方法可以省略】,按照“类型”自动装配
            如果类型冲突则按照"名称"装配 方法名由注入类的标签定义

3.其他类型注解

        @Primary
            含义:在类型装配冲突的情况下,此注解所修饰的类作为首选项
            位置:修饰类,与四个类标签共同使用
        @Qualifier
            含义:按照名称装配
            位置:修饰属性,与@Autowired搭配使用
                  在@Autowired找到对象实现类后,按照Qualifier的value选取类
        @Resource
            含义:按照名称装配,关键字为name
            位置:修饰属性,单独用,作用==@Autowired+@Qualifier
        @Scope
            含义:作用域
            位置:与注入类的四个标签一同修饰类,使创建单例对象或多例对象
            举例:@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
        @PreDestroy
            含义:替换destory-method:销毁
            位置:方法
            注意:单独用
        @PostConstruct
            含义:替换init-method:初始化
            位置:方法
            注意:单独用

三.以annonation+javaConfig配置类形式注入依赖

1.@Configuration

作用: 所修饰的文件便是配置类,代替了xml文件

注意:使用AnnotationConfigApplicationContext(配置类.class)实现类获取依赖

2.@ComponentScan

作用: 替换:<context:component-scan base-package=""></context:component-scan>,修饰配置类

3.@PropertySource()

作用: 替换:<context:property-placeholder location=""></context:property-placeholder>,修饰配置类

4.@Import() 含义:导入其他配置类,写在主配置类中

5.@Bean 含义:直接在配置类中注入方法,修饰方法,无需扫描注入类

方法返回值为class 方法名称为id

//向容器中注入id为ta且class为Teacher的类
    @Bean(name = "ta")
    public Teacher teacher(){
        return  new Teacher();
    }

 向上攀爬的痛苦,终会在登顶时烟消云散
——ZQY

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜鸟0917

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值