Issue
I want to create bean, but it tells me you can't have field of type string or other type those their class declaration not include anotation @Component. ex .
@Component
public class MyDependancy {
private String name;
MyDependancy(){}
MyDependancy(String name){this.name = name }
// setter and getter of name field
}
it show compiler error : Could not autowire. No beans of 'String' type found. when I add @Autowired before declaration of name String, is give the same compiler error.
Solution
You need to create your bean explicitly in the configuration. You don't need any autowiring inside your class:
public class MyDependancy {
private String name;
MyDependancy(){}
MyDependancy(String name){this.name = name }
// setter and getter of name field
}
And in the @Configuration
class:
@Bean
public MyDependancy myDependancy() {
return new MyDependancy("Hello");
}
And then, from anywhere you can call to (this is just for example, please use setter\c'tor autowiring):
@Autowired
private MyDependancy myDependancy;
You can inject the name
property in other ways as well.
Answered By - Shay Zambrovski
Answer Checked By - Mildred Charles (JavaFixing Admin)