Spring annotation Component
In the previous article, we described dependency injection annotations in detail, especially @ Autowired. However, our bean definition declaration is still placed in the xml configuration file. Of course, Spring provides a mechanism to automatically scan class paths and automatically register BeanDefinition with the container. This is Bean-level annotation. The above mechanism is called clsspath-sacn. It has related annotations (such as @ Component @ Named @ Bean) and beanFactoryPostProcessor and BeanPostProcessor. This article describes the annotations in sequence.
The sample code used in this article inherits the previous chapter. First, let's look at the annotations.
@ Component meta Annotation
This is a meta annotation, which means it can be used to annotate other annotations, And the annotation labeled by it plays the same or similar role. Spring uses it to define other annotations with specific meanings, such as @ Controller @ Service @ Repository. The following is the definition of @ Service in Spring:
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component // Spring will see this and treat @Service in the same way as @Component public @interface Service { }
In addition, @ Controller and @ Repository are similar. Spring gives these annotations special meanings in web projects. Controller and data access layer.
Custom
We can customize annotations as follows:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @interface MyComponent {String value();}
Use
We can now use the (custom) annotation to Directly mark a class, and this class will be automatically registered as BeanDefinition by the Spring container, we can declare the bean defined in xml in the previous article by modifying the annotation method:
// Use the meta annotation @ Component ("user1") public class UserServiceIml1 implements UserService {private UserDao userDao; @ Override public List
GetUser () {return userDao. getUser () ;}// mark it on the set method. @ Autowired public void setUserDao (@ Qualifier ("userDao") UserDao userDao) {this. userDao = userDao ;}}
// Use the custom annotation @ MyComponent ("user2") public class UserServiceIml2 implements UserService {// Annotation on the field. @ Autowired @ Qualifier ("userDao") private UserDao userDao; @ Override public List
GetUser () {return userDao. getUser ();}}
After the annotation is used, we need to configure Spring to enable classpath-scan. In the XML configuration, add the following Configuration, this configuration automatically enables annotation-related functions:
The preceding annotation indicates that the class in the @ component (or its extension) table under the com. test package and its sub-package is automatically scanned and registered as bean. The preceding configuration also has other attributes, which can be used to define specialized filters for custom configuration.
The following is an example:
@ Bean
When using XML to configure beans, we can use the instance factory to define a bean. Using the @ Bean annotation, we can do the same. Define Another Bean in a Bean. This is done by using @ Bean to annotate a method in the annotation class of @ Component.
As follows:
@Bean(name="getService") @Qualifier("getService") public UserService getService(@Qualifier("userDao") UserDao user){ UserService ser = new UserServiceIml1(); return ser; }
The above defines a Bean and defines the Name and Qualifier attributes. You can also define attributes such as Scope and Lazy. See the next section.
In fact, @ Bean is mostly used together with @ Confuguration to build an annotation-based AnnotationConfigApplicationContext different from the XML-based ApplicationContext. This will be discussed later.
Naming and other attributes
The annotation has a value Attribute Based on the annotation of @ Componet and Its Extensions (such as @ Servic and custom) and the Bean defined by classpath-scan. If so, the Bean name is provided. If not. The default naming mechanism of Spring is used, that is, the simple class name with the first letter in lowercase. See the following example:
@ Component ("user5") // The Bean name is user5public class UserServiceIml5 implements UserService {}@ Component () // The Bean name is userServiceIml3public class UserServiceIml3 implements UserService {}
We can update the default naming mechanism of Spring, as long as we implement the relevant interface BeanNameGenerator and configure it as follows:
Others
In XML-based configuration, bean labels also have many attributes, such as scope, Lazy, init-method, depends-on, and Qualifier. The following is a simple configuration example:
Package com. test. service; import java. util. list; import org. springframework. beans. factory. annotation. autowired; import org. springframework. beans. factory. annotation. qualifier; import org. springframework. context. annotation. bean; import org. springframework. context. annotation. dependsOn; import org. springframework. context. annotation. lazy; import org. springframework. context. annotation. scope; import org. springframework. context. annotation. scopedProxyMode; import org. springframework. stereotype. component; import com. test. bo. user; import com. test. dao. userDao; import com. test. dao. userDaoImp; import com. test. service. userService; // use the meta annotation @ Component ("user1") @ Qualifier ("user1") @ Lazy (true) @ DependsOn ("userDao ") public class UserServiceIml1 implements UserService {private UserDao userDao; @ Override public List
GetUser () {return userDao. getUser () ;}// mark it on the set method. @ Autowired public void setUserDao (@ Qualifier ("userDao") UserDao userDao) {this. userDao = userDao;} @ Bean (name = "getService", initMethod = "init1", destroyMethod = "close1") @ Qualifier ("getService ") @ Scope (value = "singleton") @ Lazy (true) @ DependsOn ("getDao") public UserService getService (@ Qualifier ("getDao") UserDao user) {System. out. println ("------------ getService is creted when used ------------"); System. out. println (user. getClass (). toString (); UserService ser = new UserServiceIml1 (); return ser ;}@ Bean (name = "getDao") @ Qualifier ("getDao ") @ Scope (value = "prototype", proxyMode = ScopedProxyMode. TARGET_CLASS) @ Lazy (true) public UserDao getDao () {System. out. println ("------------ getDao is creted when used ------------"); return new UserDaoImp ();} private void init1 () {System. out. println ("--------- getService init1 ----------------");} private void close1 () {System. out. println ("--------- getService close ----------------");} public UserDao getUserDao () {return userDao ;}}
The above mentioned attributes are added to the class and a method respectively, which can be compared with the configuration of traditional XMl. A proxy must be generated when major singleton references other types.
@ Configuration
Spring provides an annotation-based applicationContext. In actual applications, it can be used together with XML configurations or separately. The @ Bean annotation requires a lot of use when using it.
The following is a simple example. For other detailed examples, see the official Spring documentation.
The first is @ConfigurationThe configuration class defines two beans.
@Configurationpublic class MyAnnoConfig { @Bean(name="cDao1") public UserDao getConfigDao(){ return new UserDaoImp(); } @Bean(name="cs1") public UserService getConfigS(@Qualifier("cDao1") UserDao dao){ UserServiceIml us =new UserServiceIml(); us.setUserDao(dao); return us; } }
The following is a test function.
public class TestAnnoContextMain { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(MyAnnoConfig.class); UserService us = ctx.getBean("cs1",UserService.class); System.out.println(us.getUser()); }}
Summary
This article describes in detail how to use Bean-level annotations supported by Spring. It mainly introduces @ Component and @ Bean (used in @ component ), some Bean attribute annotations are introduced in this section. Finally, pay attention to the example of the annotation-based applicationContext and @ configuration of Spring.
Note that this article does not introduce the annotation @ Named of the JSR-330, which is basically the same as @ Component, but not as powerful as the former. In addition, I think that as long as the principle and usage of a method are clear, the other examples are like =, this is also the reason for not writing @ configuration in detail (in fact, it works with @ Bean, and the XML-based configuration function is almost the same ). The complete test code is 0 Points