通过注解来给属性赋值
value 可以给简单类型注入
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
可以用在这些地方
Autowired 根据类型装配,想要使用根据名字装配需要@Qualifier的配合
但是我们可以用resources注解,这个注解更加推荐使用,是根据名字装配的,可能装配引用类型,可以用在属性上。强大的不得了呀哈哈哈哈
官方更加推荐使用
但是我们需要引入依赖
<dependency> <groupId>jakarta.annotation</groupId> <artifactId>jakarta.annotation-api</artifactId> <version>2.1.1</version> </dependency>
引入依赖后就可以通过名字了
我们先来个类
@Component("role")
public class Role {
@Value("绘梨衣小巫女")
private String name ;
public String print(){
return this.name;
}
}
然后在Role2中使用Role
@Service("role2")
public class Role2 {
@Resource(name = "role")
private Role role;
@Value("绘梨衣2")
private String name ;
public void print(){
System.out.println(this.name);
}
public void print2(){
System.out.println(role.print());
}
}
然后在 @Resource(name = "role")
private Role role; 就可以了
结果如下
绘梨衣2
绘梨衣小巫女