When using component scanning, you need to specify the scan path in the XML configuration now
<context:component-scan back-package="yangjq.test">
Container instantiation scans all component classes under the yangjq.test package and its subpackage.
Only when component class definitions are preceded by the following annotation marks, these component classes will be scanned into the Spring container.
- @Component General Annotation
- @Name General annotation
- @Repository Persistence Layer Component Annotation
- @Service Business layer component annotation
- @Controller Control layer component annotation
name
The component will generate a default id value (class name starting with lowercase) during the scanning process. This can also be customized in the annotation mark, such as:
//This is the default id, the value is OracleUserDao@Repositorypublic class OracleUserDao implements UserDao{}//This is a custom id, the value is loginService@Service("loginService")public class UserService{}Component scope
The default scope of Spring-managed components is "singleton". If you need other scopes, you can use @Scope annotation, just provide the scope name in the annotation.
@Scope("prototype")@Repositorypublic class OracleUserDao implements UserDao{}Initialization and destruction
@PostConstruct and @PreDestroy annotation tags are used to specify the initialization and destruction callback methods, such as:
public class ExampleBean{@PostConstruct public void init(){//.........Initialization}@PreDestroy public void destroy(){//......Destroy}}Annotation for Beans with dependency injection relationship
It can use any of the following to implement relational injection
- @Resource
- @AutoWired/@Qualifier
- @Inject/@Named
Usually, there are many @Resources used, so let’s talk about @Resource. If you use the others, search and read them.
@Resource annotation tags can be used before field definitions or setter method definitions. By default, first match injection is used by name, and then type match injection.
public class UserSerivce{//@Resource This is used to define private UserDao userDao;@Resource //This is used to precede the setter method public void setUserDao(UserDao dao){this.UserDao=dao;}}An error occurs when multiple matching beans are encountered. You can specify a name explicitly, such as @Resource(name=”exampleDao”).
Summarize
The above is all the detailed explanation of annotation-based component scanning, and I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!