Spring学习 ---- bean的依赖注入

bean的依赖注入

依赖装配就是为类中的属性赋值,或者说初始化。

使用构造器进行依赖注入

  • 根据构造方法的参数名称为属性赋值(不是属性的名称)
<bean id="user" class="com.xust.excellent.review.User">
        <constructor-arg name="name" value="zs"/>
        <constructor-arg name="age" value="1"/>
        <constructor-arg ref="date"/>
 </bean>

注:当多个构造方法的参数名称相同时,将会发生问题。

 public User(String age){
        System.out.println("字符串参数" + age);
    }
    public User(int age){
        System.out.println("整型参数" + age);
   }
   
   <bean id="user" class="com.xust.excellent.review.User">
        <constructor-arg name="age" value="20"/>
    </bean>

最终配置的是String类型。

  • 通过构造方法参数的索引或者类型为属性赋值
 <bean id="user" class="com.xust.excellent.review.User">
 		// 索引
        <constructor-arg index="0" value="zs"/>
        // 类型
        <constructor-arg type="java.lang.Integer" value="10"/>
        <constructor-arg ref="date"/>
    </bean>

通过类型或者索引都需要记住具体的参数的位置或者类型,当构造方法的参数较多时,会带来记忆负担,不方便使用。因此了解即可。

注:类型配置过程中,不会发生自动拆装箱。

通过setter方法依赖注入

<bean id="user" class="com.xust.excellent.review.User">
        <property name="name" value="zs"/>
        <property name="age" value="10"/>
        <property name="birthday" ref="date"/>
    </bean>

使用这种方法,类中必须提供相应属性的setter方法。

idref 和 ref 的区别:

  • idref:使用id值为属性初始化。
  • ref:使用id值对应的bean为属性初始化。

注解注入

  • Sping默认是关闭注解的,因此需要手动开启
    <!--开启注解-->
    <context:annotation-config/>
    <!--指定扫描的包的范围-->
    <context:component-scan base-package="com.github.excellent"/>
@Data
@Component    
public class User {
    private String name;
    private Integer age;

    public static void main(String[] args) {
        ApplicationContext context = new 
        				ClassPathXmlApplicationContext("bean.xml");
        System.out.println(context.getBean(User.class));
    }
}
  • @Component 没有配置id时,可以通过类型获取。配置了id也可以通过类型获取。
  • 类型可以是,类的类型也可以是实现的接口的类型。
根据属性自动注入

@Autowired自动装配 ,当容器中含有相应类型的对象时,便会自动注入

@Data
@Component

public class User {
    @Autowired
    private Computer computer;
    private Integer age;
    @Autowired
    private Stu stu;
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        System.out.println(context.getBean(User.class));
    }
}
根据指定id注入
public class User {
    @Autowired
    private Computer computer;
    private Integer age;
    @Qualifier("stu")
    private Stu stu;
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        System.out.println(context.getBean(User.class));
    }
}
@Data
@Component("stu")
class Stu{
    private String name;

}
  • 一般不需要指定id,自动注入就行。
直接注入
 @Value("100")
    private Integer age;
  • 为属性直接赋值
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值