In previous projects, we all assigned beans or certain attributes through XML files. In fact, there is another way to annotate. It is used a lot in enterprise development. Adding annotations on the beans can quickly register the beans to the ioc container.
1. Register beans into IOC container using annotations
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="/schema/beans" xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:context="/schema/context" xsi:schemaLocation="/schema/beans /schema/beans/ /schema/context /schema/context/"> <!-- Use annotations as follows:: 1、Add any of the four comments above 2、Add components that automatically scan annotations,This operation requires dependenciescontextNamespace 3、Add automatic scanning tagscontext:component-scan Notice:When registering components with annotations is the same as registering components with configuration files,但是要Notice: 1、Componentid默认就是Component类名首字符小写,If you have to change your name,Just add it to the annotation 2、Components are singleton by default,If you need to configure multiple modes,You can add it under the annotation@Scopeannotation --> <!-- Define the basic package for automatic scanning: base-package:Specify the scanned basic package,spring在启动的时候会将基础包及子包下所有加了annotation的类都自动 Scan intoIOCcontainer --> <context:component-scan base-package=""></context:component-scan> </beans>
package ; import ; @Controller public class PersonController { public PersonController() { ("Create an object"); } }
package ; import ; @Service public class PersonService { }
package ; import ; @Repository("personDao") @Scope(value="prototype")//Default singleton, changed to prototypepublic class PersonDao { }
If you want to add a custom bean object to the IOC container, you need to add some annotations to the class
Spring contains 4 main components to add annotations:
- @Controller: Controller, it is recommended to add this annotation to the controller layer
- @Service: Business logic, it is recommended to add this annotation to the business logic layer
- @Repository: Repository management, it is recommended to add this annotation to the data access layer
- @Component: Add this annotation to components that do not belong to the above base layer
Notice: Although we artificially add different annotations to different layers, in spring's view, we can add any annotations to any layer, but the underlying layer of spring will not give specific hierarchical verification annotations. The purpose of writing this is only to improve readability. The lazy way is to add component annotations to all bean objects that want to be handed over to managed by IOC containers.
2. Define the classes to be included and the classes not to be included when scanning the package
After defining the basic scanning package, in some cases, it may be necessary to selectively configure whether to register beans into the IOC container. This can be configured in the following way.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="/schema/beans" xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:context="/schema/context" xsi:schemaLocation="/schema/beans /schema/beans/ /schema/context /schema/context/"> <context:component-scan base-package="" use-default-filters="false"> <!-- After defining the basic scan package,Some classes in the package can be excluded,Use the following method: type:Indicates the specified filtering rules annotation:Exclude according to the annotation,Components marked with specified annotations should not be,expressionIndicates the annotation to be filtered assignable:Specify excluding a specific class,Exclude by category,expressionSpecific class name indicating that it is not registered aspectj:aopUsedaspectjexpression,Generally not used custom:Define atypeFilter,Write your own code to decide which classes are filtered out,Generally not used regex:使用正则expression过滤,Generally not used --> <!-- <context:exclude-filter type="annotation" expression=""/>--> <!--Specify which components are scanned only,All scans by default,So if you want to configure it at this time, you need tocomponent-scanAdd to the tag use-default-filters="false"--> <context:include-filter type="assignable" expression=""/> </context:component-scan> </beans>
3. Use @AutoWired for automatic injection
Using annotations to achieve automatic injection requires the use of @AutoWiredannotation.
package ; import ; import ; import ; @Controller public class PersonController { @Autowired private PersonService personService; public PersonController() { ("Create an object"); } public void getPerson(){ (); } }
package ; import ; import ; import ; @Service public class PersonService { @Autowired private PersonDao personDao; public void getPerson(){ (); } }
package ; import ; @Repository public class PersonDao { public void getPerson(){ ("PersonDao:getPerson"); } }
Note: When using AutoWired annotations, automatic assembly is implemented according to the type.
1. If only one is found, then the value will be assigned directly.
2. If not found, the exception will be thrown directly.
3. If multiple are found, the variable name will continue to match according to the id.
- Direct assembly on matching
- If the match is not up, the exception will be reported directly
package ; import ; import ; import ; @Service public class PersonServiceExt extends PersonService{ @Autowired private PersonDao personDao; public void getPerson(){ ("PersonServiceExt......"); (); } }
package ; import ; import ; import ; @Controller public class PersonController { @Autowired private PersonService personServiceExt; public PersonController() { ("Create an object"); } public void getPerson(){ (); } }
You can also use @QualifierAnnotation to specify the name of the id, so that spring does not use variable names, when using @QualifierThere are also two situations when annotating:
1. Find it, then assemble it directly
2. If it cannot be found, an error will be reported
package ; import ; import ; import ; import ; @Controller public class PersonController { @Autowired @Qualifier("personService") private PersonService personServiceExt2; public PersonController() { ("Create an object"); } public void getPerson(){ (); } }
Through the above code, we can find that using @AutoWired can definitely be assembled, and if it cannot be assembled, an error will be reported.
4. @AutoWired can be defined on the method
When we check @AutoWiredWhen I was annotated, I found that this annotation can be used not only on member variables, but also on methods.
package ; import ; import ; import ; import ; import ; @Controller public class PersonController { @Qualifier("personService") @Autowired private PersonService personServiceExt2; public PersonController() { ("Create an object"); } public void getPerson(){ ("personController..."+personServiceExt2); // (); } /** * When there is @AutoWired annotation on the method: * 1. This method will be automatically called when the bean is created. * 2. Each parameter of this method will automatically inject value * @param personDao */ @Autowired public void test(PersonDao personDao){ ("This method is called:"+personDao); } /** * @Qualifier annotation can also be used on attributes and is used as id to match objects in the container, if not * This annotation will be matched directly according to the type. * @param personService */ @Autowired public void test2(@Qualifier("personServiceExt") PersonService personService){ ("This method is called:"+personService); } }
5. Automatic assembly annotation @AutoWired, @Resource
When using automatic assembly, you can use @AutoWired annotation, you can also use @Resource annotation.
1、@AutoWired: is an annotation provided in spring, @Resource: is an annotation defined in jdk, relying on the Java standard
2、@AutoWiredBy default, it is assembled by type. By default, the dependency object must exist. @ResourceThe default is to match by name, and the name attribute can be specified.
3、@AutoWiredOnly suitable for spring frameworks, and @ResourceBetter scalability
package ; import ; import ; import ; import ; import ; import ; @Controller public class PersonController { @Qualifier("personService") @Resource private PersonService personServiceExt2; public PersonController() { ("Create an object"); } public void getPerson(){ ("personController..."+personServiceExt2); (); } /** * When there is @AutoWired annotation on the method: * 1. This method will be automatically called when the bean is created. * 2. Each parameter of this method will automatically inject value * @param personDao */ @Autowired public void test(PersonDao personDao){ ("This method is called:"+personDao); } /** * @Qualifier annotation can also be used on attributes and is used as id to match objects in the container, if not * This annotation will be matched directly according to the type. * @param personService */ @Autowired public void test2(@Qualifier("personServiceExt") PersonService personService){ ("This method is called:"+personService); } }
6. Generic Dependency Injection
In order to understand generic dependency injection, we need to write a basic case first:
package ; public class Student { }
package ; public class Teacher { }
package ; import ; @Repository public abstract class BaseDao<T> { public abstract void save(); }
package ; import ; import ; @Repository public class StudentDao extends BaseDao<Student>{ public void save() { ("Save Students"); } }
package ; import ; import ; @Repository public class TeacherDao extends BaseDao<Teacher> { public void save() { ("Save Teacher"); } }
package ; import ; import ; import ; @Service public class StudentService { @Autowired private StudentDao studentDao; public void save(){ (); } }
package ; import ; import ; import ; @Service public class TeacherService { @Autowired private TeacherDao teacherDao; public void save(){ (); } }
import ; import ; import ; import ; import ; import ; public class MyTest { public static void main(String[] args) throws SQLException { ApplicationContext context = new ClassPathXmlApplicationContext(""); StudentService studentService = ("studentService",); (); TeacherService teacherService = ("teacherService",); (); } }
The above code can complete the corresponding functions, but the code in the Service layer can be rewritten as:
package ; import ; import ; import ; public class BaseService<T> { @Autowired BaseDao<T> baseDao; public void save(){ ("Auto-injected object:"+baseDao); (); } }
package ; import ; import ; import ; import ; @Service public class StudentService extends BaseService<Student> { }
package ; import ; import ; import ; import ; @Service public class TeacherService extends BaseService<Teacher>{ }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.