[英]no qualifying bean of type 'java.lang.string' available error in spring
I am getting no qualifying bean of type 'java.lang.string' available error in spring, NoSuchBeanDefinitionException in the following code.我在 spring 中没有收到类型为“java.lang.string”的合格 bean 可用错误,在以下代码中出现 NoSuchBeanDefinitionException。 I have Test.java like the following, where I am trying to read the value from application.yaml.
我有如下所示的 Test.java,我试图从 application.yaml 中读取值。
@Configuration
public class Test {
@Value("${value}")
private String val;
@Bean
public Vehicle getVehicle() {
return new Vehicle(val);
}
}
In Vehicle.java在 Vehicle.java 中
@AllArgConstructor
@Getter
@Setter
public class Vehicle {
private String model;
}
I have another class, Driver.java, from where I have to inject Vehicle object through constructor.我有另一个类 Driver.java,我必须从其中通过构造函数注入 Vehicle 对象。
@Service
public class Driver {
private Vehicle v;
@Autowired
public Driver(Vehicle v) {
this.v = v;
}
application.yaml looks like this. application.yaml 看起来像这样。
value: FORTUNE
price: 10000
You can try a different way to inject this:你可以尝试一种不同的方式来注入它:
You don't need to create a configuration class where you inject the property as field and then create a bean of Vehicle.您不需要创建一个配置类,在其中将属性作为字段注入,然后创建 Vehicle 的 bean。 You can use constructor injection in Vehicle and make Vehicle a Component with
@Component
annotation;您可以在 Vehicle 中使用构造函数注入,并使 Vehicle 成为带有
@Component
注释的组件;
@Getter
@Setter
@Component
public class Vehicle {
private String model;
public Vehicle(@Value("${value}") String model) {
this.model = model
}
}
I personally prefer this way and I hope it works for you!我个人更喜欢这种方式,我希望它对你有用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.