使用注解注入Bean
在Spring中,如果你不使用XML配置文件,可以通过以下几种方式注入Bean:
1. 使用注解 (@Component、@Service、@Repository、@Controller) 和 @Autowired
1.1 @Component 注解
@Component 注解用于标注一个普通的Spring Bean,它会自动注册为Spring的组件,Spring容器会自动扫描并管理这些Bean。
@Component
public class Engine {
// Engine implementation
}
1.2 @Service, @Repository, @Controller 注解
这些注解是 @Component 的特殊化,分别用于标注服务层、数据访问层和控制层的Bean。
@Service
public class CarService {
// Service implementation
}
@Repository
public class CarRepository {
// Repository implementation
}
@Controller
public class CarController {
// Controller implementation
}
1.3 @Autowired 注解
@Autowired 注解用于自动装配依赖,Spring会自动在容器中查找并注入符合要求的Bean。
@Component
public class Car {
private final Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
}
可以将 @Autowired 放在构造器、Setter方法,或字段上。
@Component
public class Car {
@Autowired
private Engine engine;
public Engine getEngine() {
return engine;
}
}
Spring一共有几种注入方式
构造器注入:Spring 倡导构造函数注入,因为构造器注入返回给客户端使用的时候一定是完整的。
setter 注入:可选的注入方式,好处是在有变更的情况下,可以重新注入。
字段注入:就是平日我们用 @Autowired 标记字段
方法注入:就是平日我们用 @Autowired 标记方法
接口回调注入(不常用):就是实现 Spring 定义的一些内建接口,例如 BeanFactoryAware,会进行 BeanFactory 的注入
字段注入的缺点: 其实官方是不推荐使用的,因为依赖注解后,没有控制注入顺序且无法注入静态字段
构造器注入:构造器函数传递依赖
public class MyService {
private final MyDependency myDependency;
@Autowired
public MyService(MyDependency myDependency) {
this.myDependency = myDependency;
}
}
seeter注入:setter方法设置
public class MyService {
private MyDependency myDependency;
@Autowired
public void setMyDependency(MyDependency myDependency) {
this.myDependency = myDependency;
}
}
字段注入:直接在字段上使用@Autowired注解
public class MyService {
@Autowired
private MyDependency myDependency;
}
方法注入:通过方法参数注入依赖项,通常用于特定方法的依赖
public class MyService {
public void performAction(@Autowired MyDependency myDependency) {
myDependency.doSomething();
}
}