Home > Software engineering >  class being Annotated by @componenet can't have non Autowired fields
class being Annotated by @componenet can't have non Autowired fields

Time:01-16

I want to create bean, but it tells me to not have field of type string or other type those their class definition not include @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.

CodePudding user response:

It should work in the latest version of Spring as this behaviour is mentioned in docs as follows :

Similarly, if a class declares multiple constructors but none of them is annotated with @Autowired, then a primary/default constructor (if present) will be used.

As your example shows you do define a default constructor , so it should be used to create MyDependancy bean.

So I believe you are using an old version of Spring , most probably a version before 4.3 ?

CodePudding user response:

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:

@Autowired
private MyDependancy myDependancy;

You can inject the name property in other ways as well.

  •  Tags:  
  • Related