一、@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);
}
}