Spring declaration @Autowired and bean in applicationContext.xml

Hi I am relatively new to spring. I use annotations. I doubt that I have class a

public class MyClassA{ @Autowired private MyClassB variableClassB; // more code here . . . 

in my application context.xml

 <context:component-scan base-package="package containing MyClassB" /> 

My question is: I need to add a bean declaration in applicationContext.xml as follows

 <bean id="classB" class="com.MyClassB" 

or enough for @Autowired annotation

+4
source share
4 answers

No, it is not.

If your MyClassB annotated with annotations like @Component , @Service , @Repository or @Controller , component scanning will create a bean for the class in the bean factory.

If you are not using any of these annotations, you need to create a bean manually as you indicated

Example:

 @Component public class MyClassB{ } 
+6
source

If you have the @Component annotation on MyClassB , there is no need to add <bean id="classB" class="com.MyClassB" in applicationContext.xml. Otherwise, necessary.

+1
source

The whole purpose of the @Autowired annotation is to avoid explicitly mentioning the bean in the xml file. Performance

<context:component-scan base-package="package containing MyClassB" />

checks the package and looks for annotations @Controller , @Service , @Repository , etc. and makes a bean himself.

+1
source

The @Autowired annotation avoids explicitly indicating the need for MyClassB in the MyClassB XML MyClassA , but this does not mean that the MyClassB bean is created automatically. If you don't want to have MyClassB in XML at all, you need to do context:component-scan to find @Bean (and derivatives) annotations. (Scanning is quite expensive, so you need to ask for it explicitly.)

+1
source

Source: https://habr.com/ru/post/1491374/


All Articles