Java code
@ Retention (RetentionPolicy. RUNTIME)
@ Target ({ElementType. CONSTRUCTOR, ElementType. FIELD, ElementType. METHOD })
Public @ interface Autowired {
/**
* Declares whether the annotated dependency is required.
* <P> Defaults to <code> true </code>.
*/
Boolean required () default true;
}
@ Retention (RetentionPolicy. RUNTIME)
@ Target ({ElementType. CONSTRUCTOR, ElementType. FIELD, ElementType. METHOD })
Public @ interface Autowired {
/**
* Declares whether the annotated dependency is required.
* <P> Defaults to <code> true </code>.
*/
Boolean required () default true;
} We know from the source code that it is an annotation interface of spring and there is a method.
Java code
Boolean required () default true;
Boolean required () default true;
The following conditions must be met:
1. The spring configuration file must be added with something that can recognize annotations.
Org. springframework. beans. factory. annotation. AutowiredAnnotationBeanPostProcessor
Or use xml to mark the following (note the version)
Xmlns: context
<Context: component-scan base-package = "org. javaeye. *"/>
Four annotations are supported: @ Component, @ Serivce, @ Controller, and @ Repository.
@ Controller: Control Layer
@ Serivce: business logic layer
@ Repository: Persistence Layer
2. Annotations exist.
Java code
@ Autowired
UserService userService;
@ Autowired
UserService userService; 3. Corresponding setter Method
Java code
Public void setUserService (UserService userService ){
This. userService = userService;
}
Public void setUserService (UserService userService ){
This. userService = userService;
} 4. If it is an interface or an abstract class, the class must be unique; otherwise, an error occurred while creating the instance.
Java code
Org. springframework. beans. factory. NoSuchBeanDefinitionException:
No unique bean of type
[Com. sohu. suc. splatform. service. UserService] is defined:
Expected single matching bean but found 2:
[UserServiceHibernateImpl, userServiceImp]
Org. springframework. beans. factory. NoSuchBeanDefinitionException:
No unique bean of type
[Com. sohu. suc. splatform. service. UserService] is defined:
Expected single matching bean but found 2:
[UserServiceHibernateImpl, userServiceImp]
5. The implementation of interfaces must be known to spring, and spring needs to be aware of them by bean configuration or annotation.
Java code
@ Service
Public class UserServiceImpl implements UserService {
.......
}
@ Service
Public class UserServiceImpl implements UserService {
.......
} In summary, spring only manages the bean he knows. There are two ways to let spring know the existence of bean.
1. annotation Method
2. bean Configuration