spring ioc--自动装配,方法注入

通过配置default-autowire 属性,Spring IOC 容器可以自动为程序注入bean;默认是no,不启用自动装配;
default-autowire 的类型有byName,byType,constructor;
byName:通过名称进行自动匹配;
byType:根据类型进行自动匹配;
constructor:和byType 类似,只不过它是根据构造方法注入而言的,根据类型,自动注入;

<beans......default-autowire="constructor">

 

 

  

Spring bean 作用域默认是单例singleton; 可以通过配置prototype ,实现多例;
方法注入lookup-method

package entity;

public class Dog {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    
}

 

public abstract class People {

    private int id;
    private String name;
    private int age;
    private Dog dog;
    
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public abstract Dog getDog();
    
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    @Override
    public String toString() {
        return "People [id=" + id + ", name=" + name + ", age=" + age
                + ", dog=" + dog.getName() + "]";
    }
}
<?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 -->    
    <bean id="dog" class="entity.Dog" scope="prototype">
        <property name="name" value="Jack"></property>
    </bean>
    
    
    
    <bean id="people1" class="entity.People">
        <property name="id" value="1"></property>
        <property name="name" value="张三"></property>
        <property name="age" value="11"></property>
        <lookup-method name="getDog" bean="dog"/>
    </bean>
    
</beans>

 

转载于:https://www.cnblogs.com/lcpholdon/p/4508649.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值