Spring annotation-based injection bean (xiv)

1. @ Autowired annotations are automatically assembled by matching the data type Bean

Plus @Autowired injects in accordance with the type or properties of the above-configured by the above method or the setter method byType.

Need to use @Autowired, need to configure the file to start the annotations, the annotations take effect:

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

or

<context:annotation-config />

@Autowired has the following usage:

	//setter
	@Autowired
	public void setPerson(Person person) {
		this.person = person;
	}
	//构造
	@Autowired
	public Customer(Person person) {
		this.person = person;
	}
	//属性
	@Autowired
	private Person person;

@Autowired annotation using default dependency checking, when Q is not present in the vertical configuration of this type of bean will throw an exception, dependency checking may not be performed by setting, as follows:

@Autowired(required=false)

When two of the same type exist in the configuration context bean, @ Autowired accordance injection type will throw an exception may indicate that the bean injection @Quanlifier, as follows:

	@Autowired
	@Qualifier("personA")
	private Person person;

2. @ Resource annotation

@Autowired @Resource annotation and use substantially the same,

1, @ Resource back no content, by default name to match the bean property, not found to match press type
2, or type name specified to match the specified bean type
3, and specifies the name of the specified type the name and type to match the bean, any error will be a mismatch

Then, the distinction about the difference between two @Resource @Autowired and annotation:
1, @ Autowired default bean were matched according to byType way, @ Resource bean default be matched according to byName way
2, @ Autowired Spring's annotation, @ Resource is a J2EE notes, this look at the import of these two notes when notes were clear picture package

Note: Spring belonging to a third party, J2EE Java is its own thing, therefore, recommend the use of @Resource annotations, to reduce coupling between code and Spring.

Guess you like

Origin blog.csdn.net/qq_36831305/article/details/89365487