Spring ----- annotation development and Spring testing unit, spring ----- spring
I. annotation Development
<Context: component-scan base-package = "com. itheima"/>
/* 1. @ Component, indicating to host this class and let spring create the class instance. The us in the brackets is actually the id Identifier 2. @ Component is a common annotation that can be used for any hosted class. However, spring also provides specific annotations for each layer to cater to the three-tier architecture. Action --- @ Controller Service --- @ Service Dao --- @ Repository: Repository. We recommend that you use the corresponding annotations if you host classes on the third layer later. If you host other classes. @ Component 3. the default instance is still a singleton. If you want to create multiple instances, you must add an annotation @ Scope ("prototype") 4. @ PostConstruct // call @ PreDestroy when initializing the instance // call 5 before destroying the instance. if an annotation is used to host a class without specifying the attribute value, the default id Identifier is userServiceImpl 6. <! -- If you want to scan multiple packages, write a general prefix --> <context: component-scan base-package = "com. itheima"/> */
DI Annotation
Use annotations to complete dependency injection. Generally, annotation injection is targeted at object injection. Spring provides two annotations for object injection: @ Resource and @ Autowired. There are two commonly used Annotations: @ Resource & @ Autowired @ Resource (name = "ud ") find the corresponding class based on the given tag, create an object, and inject it in. @ Autowired: automatically assemble, find the corresponding implementation class creation object, and inject it in. However, if multiple implementations exist, an exception is thrown.
Ii. Spring testing unit
// Spring extends the running environment of junit. In addition to testing functions, it also defines the code for creating a factory @ RunWith (SpringJUnit4ClassRunner. class) // tell the spring test environment where the configuration file is located @ ContextConfiguration ("classpath: applicationContext. xml ") public class TestUserService {// annotation in the test class. You do not need to enable the scan switch. Because in this test environment, it will parse the annotation of this test class. @ Autowired private UserService userService; @ Test public void testSave () {userService. save ();}}