美文网首页
SpringBean的配置

SpringBean的配置

作者: 叫我小码哥 | 来源:发表于2018-04-21 17:28 被阅读0次

Spring配置Bean并且将一个类的对象同过构造器和set方法的方式注入到另一个类中。

接下来我们就将A的对象通过构造器和set方法的方式注入到B类中。

public class A {
    public void say(){
        System.out.println("I am A");
    }   
}

public class B {
    private A a;
    public B(){}    
    public B(A a){
        this.a = a;
    }   
    public A getA() {
        return a;
    }

    public void setA(A a) {
        this.a = a;
    }
    
    public void Bshow(){
        a.say();
    }
}

Bean的配置文件
1.通过构造方法注入

<?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">

    <bean id="a" class="com.cn.dao.A"></bean>
    <bean id="b" class="com.cn.dao.B">
        <constructor-arg type="com.cn.dao.A" ref="a"></constructor-arg>
    </bean>
</beans>

2.通过Set方法的形式注入

<?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">

    <bean id="a" class="com.cn.dao.A"></bean>
    <bean id="b" class="com.cn.dao.B">
        <property name="a" ref="a"></property>
    </bean>
</beans>

相关文章

网友评论

      本文标题:SpringBean的配置

      本文链接:https://www.haomeiwen.com/subject/mvoxlftx.html