IOC操作Bean管理(基于注解)-实现属性注入

17 篇文章 0 订阅

1.@AutoWired:

  • 根据类型自动注入
    示例:(在Service层注入Dao层的属性)
第一步:

在service和dao类添加创建对象注解
注意:在实现类加注解

  • service:
    在这里插入图片描述

  • dao:
    在这里插入图片描述

第二步
  • 在service类中添加dao属性对象,在属性上边使用注解
    在这里插入图片描述

测试是否成功:

运行代码:

package com.yang.run;

import com.yang.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @program: TestSpring
 * @description: 测试注解方式是否可用
 * @author: 陈阳
 * @create: 2021-01-24 21:19
 **/
public class TestAnn {
    @Test
    public void test1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
}

运行结果:
在这里插入图片描述

2.@Qualifier:

  • 根据属性名称自动注入

@Qualifier注解使用要和@Autowired一起使用

演示:

  • dao:
    在这里插入图片描述
  • service
    在这里插入图片描述

测试是否成功:

运行代码:

package com.yang.run;

import com.yang.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @program: TestSpring
 * @description: 测试注解方式是否可用
 * @author: 陈阳
 * @create: 2021-01-24 21:19
 **/
public class TestAnn {
    @Test
    public void test1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
}

运行结果:
在这里插入图片描述

3.@Resource:

  • 可以根据类型注入,可以根据名称注入
    示例:
    在这里插入图片描述

根据需求选取一种方式

注意:@Resource是javax.annotation.Resource中的不是Spring官方包中的,所以Spring官方不建议使用@Resource注解

4.@Value:

  • 注入普通类型属性
    1.普通类型:String.int .double等。。。。

演示:
在这里插入图片描述运行测试:
在这里插入图片描述运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值