Reputation: 113
I have 3 classes which are found in different packages in a spring boot application as follows:
Why does @Autowired
work in certain classes only?Anything I am doing wrong?
@Configuration
public class Configurations{
@Autowired
Prop prop; //works fine
@Bean
//other bean definitions
}
@Component
public class Prop{
public void method(){};
}
public class User{
@Autowired
Prop prop; //does not work, null
public void doWork(){
prop.method();
}
}
I have also tried the @PostConstruct
, but same result
public class User{
@Autowired
Prop prop; //does not work, null
@PostConstruct
public void doWork(){
prop.method();
}
}
Upvotes: 2
Views: 5549
Reputation: 44745
The @Autowired
annotation works only if Spring detects that the class itself should be a Spring bean.
In your first example you annotated Configurations
with the @Configuration
annotation. Your User
class on the other hand does not have an annotation indicating that it should be a Spring bean.
There are various annotations (with different meanings) to make your class being picked up by the Spring container, some examples are @Service
, @Component
, @Controller
, @Configuration
, ... . However, this only works if your class is in a package that is being scanned by the Spring container. With Spring boot, the easiest way to guarantee that is by putting your User
class in a (sub)package of your main class (the class annotated with @SpringBootApplication
).
You can also manually create your bean by writing the following method in your Configurations
:
@Bean
public User user() {
return new User();
}
In this case you don't have to annotate your User
class, nor do you have to make sure that it is in a package that is being scanned.
Upvotes: 5