SpringBean的配置

2018-04-21  本文已影响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>
上一篇 下一篇

猜你喜欢

热点阅读