Method 5 of spring dependency Injection
In spring, how does one copy the attributes of an object?
1) constructor
2) inject values to attributes using the set Method
3) p namespace
4) automatic configuration transfer (learn more, not recommended)
5) Annotation
Preparation (simulated Business Method) Action --> service --> dao
1) UserDao:
Public class UserDao {public void save () {System. out. println (save method );}}
2) UserService:
public class UserService {private UserDao userDao;public void setUserDao(UserDao userDao) {this.userDao = userDao;}public void save(){userDao.save();}}
3) UserAction:
public class UserAction {private UserService userService;public void setUserService(UserService userService) {this.userService = userService;}public String execute(){userService.save();return null;}}
4) App test class:
public class App {ApplicationContext ac=new ClassPathXmlApplicationContext(cn/itcast/property/bean.xml);@Testpublic void test(){UserAction userAction=(UserAction) ac.getBean(userAction);System.out.println(userAction.execute());}}
5) bean. xml Constraints
Method 1. set Method Injection
1) The set method must be ensured.
Method 2. Internal bean (because it is an internal bean, if there is another action, the service method in it cannot be referenced)
bean id=userAction class=cn.itcast.property.UserAction>
Method 3. p namespace
Method 4: automatic assembly (not recommended)
Method 5: Annotation
Steps for using Annotations:
1) first introduce the context namespace
Xmlns: context = http://www.springframework.org/schema/context
2) Enable annotation Scanning
3) Use annotations
Add the object to the ioc container by annotation.
Create objects and process object dependencies. Related Annotations:
@ Component specifies to add an object to the IOC container
@ Repository: Same as @ Component; used in the persistence layer
@ Service acts the same as @ Component; used at the business logic layer
@ Controller works the same as @ Component; used at the control layer
@ Resource property Injection
Enable scanning in the configuration file
UserDao uses annotations (the set method is not required if annotations are used)
@ Repositorypublic class UserDao {public void save () {System. out. println (save method );}}
UserService usage annotation:
@Servicepublic class UserService {@Resourceprivate UserDao userDao;public void save(){userDao.save();}}
UserAction usage Annotation
@Controllerpublic class UserAction {@Resourceprivate UserService userService;public String execute(){userService.save();return null;}}
The running result is: