springboot注入带参数的构造函数
时间: 2023-05-08 17:58:54 浏览: 186
在使用SpringBoot进行依赖注入时,有时需要调用带参数的构造函数进行对象的创建和初始化。在SpringBoot中,可以通过几种方式来实现带参数的构造函数注入。
1. @Autowired注解方式
可以通过在带参数的构造函数上添加@Autowired注解来实现注入。在注入时,SpringBoot会自动寻找与构造函数参数类型匹配的对象进行注入,若没有找到则会抛出NoSuchBeanDefinitionException异常。
例如:
```
@Component
public class Car {
private Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
}
```
2. @Bean注解方式
也可以通过在配置类中定义带参数的@Bean方法,然后在另一个对象中通过@Autowired注解来调用该方法获取对象实例。
例如:
```
@Configuration
public class AppConfig {
@Bean(name = "car")
public Car getCar(Engine engine) {
return new Car(engine);
}
}
@Component
public class Driver {
private Car car;
@Autowired
public Driver(@Qualifier("car") Car car) {
this.car = car;
}
}
```
3. @Value注解方式
除了以上两种方式外,还可以使用@Value注解来注入参数值到带参数的构造函数中。
例如:
```
@Component
public class Person {
private String name;
private int age;
public Person(@Value("Tom") String name, @Value("20") int age) {
this.name = name;
this.age = age;
}
}
```
以上三种方式都可以实现带参数的构造函数注入,开发人员可以根据实际情况选择适合的方式。
阅读全文
相关推荐


















