Spring中的@Autowired、@Qualifier、@Resourse、@Value注解

一、@Autowired注解

package com.bc.work.service;

public interface IPersonService {

    void eat();
}
package com.bc.work.service.impl;

import com.bc.work.service.IPersonService;
import org.springframework.stereotype.Service;

@Service
public class PersonServiceImpl1 implements IPersonService {

    @Override
    public void eat() {
        System.out.println("吃米饭");
    }
}
package com.bc.work.service.impl;

import com.bc.work.service.IPersonService;
import org.springframework.stereotype.Service;

@Service
public class PersonServiceImpl2 implements IPersonService {

    @Override
    public void eat() {
        System.out.println("吃面条");
    }
}
package com.bc.work;

import com.bc.work.service.IPersonService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {

	@Autowired
	private IPersonService personService;

	@Test
	void test() {
		personService.eat();
	}
}

在上面的代码中,使用@Autowired注入的方法,根绝IPersonService找到它的实现类,如果只有一个实现类的时候可以使用,如果有多个实现类,便会报错,系统不知道要的是哪个实现类。

@Autowired注解优先用byType,而后是byName。

二、@Qualifier注解

该注解要和上面的@Autowired一起使用,根据名称进行注入,让系统知道了我们具体要引入哪个实现类,当有多个实现类的时候,我们可以使用此方法:

package com.bc.work;

import com.bc.work.service.IPersonService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {

	@Autowired
	@Qualifier(value = "personServiceImpl2")
	private IPersonService personService;

	@Test
	void test() {
		personService.eat();
	}
}

三、@Resource注解

@Resource默认先按byName自动注入,然后再byType:

import com.bc.work.service.IPersonService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@SpringBootTest
class DemoApplicationTests {

	@Resource
	private IPersonService personServiceImpl1;

	@Test
	void test() {
		personServiceImpl1.eat();
	}
}

四、@Value注解

@Value注解用于注入普通类型的属性值

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
@Service
public class UserService {

    @Value(value = "abc")
    private String name;

    public void add(){
        System.out.println(name);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值