Spring Annotations development and testing

A, Spring annotation Development

  1.1 Spring original comment

  1.2 Spring new comment

Two, Spring integration Junit

  2.1 Original Spring Junit test questions

  2.2 spring integrating junit

 

 

 

A, Spring annotation Development

  1.1 Spring original comment  

  Spring framework light reconfiguration code, configuration is heavy influence development efficiency, it is a trend to develop annotations, annotation instead of xml profile member can simplify the configuration, to improve development efficiency. Spring original notes mainly alternative configurations so as to solve the problem of heavy configuration.

  Original notes are as follows:

Annotation Description 
@Component used for instantiating classes on Bean 
@Controller use on the web layer Bean class instantiates 
@Service layer used in the service class instantiates Bean 
@Repository dao layer used in Examples class Bean of 
@Autowired use on field dependent according to the type used to inject 
@Qualififier @Autowired used in conjunction with a dependency injection based on the name 
@Resource corresponds @ Autowired + @ Qualififier, implanting by name 
@Value injection common attributes 
@Scope denoted Bean the scope 
@PostConstruct use tagging method is the method in Bean initialization method 
@PreDestroy use this method on tagging method is a method to destroy the Bean

  To use the annotations need to be disposed on the application.xml, the scanning action is Bean configuration component at which the sub-packets and packets need to be scanned in order to identify specified using annotations configured classes, fields and methods, as follows:

<! - annotation component scan, scanning all the classes in the newspaper ->  

< context: Scan-Component Base-Package = "com.itheima" > </ context: Component-Scan >

  Test: Use @Compont or @Repository Spring identification UserDaoImpl need to instantiate an object that is created by the spring for the container.

//@Component("userDao")

@Repository("userDao") // userDao相当于xml配置的 bean的id
public class UserDaoImpl implements UserDao {
  @Override
  public void save() {
    System.out.println("save running... ...");
  }
}

  If there is dependency injection may be injected via userDao @Autowired or @ Autowired + @ Qulififier or @Resource: following

// @Component ( "that userService") 
@Service ( "that userService" ) 
 public  class UserServiceImpl the implements UserService { 
  / *
  
@Autowired
  @Qualifier ( "userDao")
  
* /
  @Resource (name = "userDao" ) // Both calls dependency injection can   Private UserDao userDao;
  @Override   
public void Save () {     userDao.save ();   } }

  Injection and .properties file data strings:

@Repository("userDao") 
public class UserDaoImpl implements UserDao { 
  @Value(
"注入普通数据")   private String str;
  @Value(
"${jdbc.driver}")   private String driver;   @Override   public void save() {     System.out.println(str);     System.out.println(driver);     System.out.println("save running... ...");   }
}
 
  Use @Scope marked Bean range
//@Scope("prototype") 
@Scope("singleton") 
@Resposity("useDao")
public class UserDaoImpl implements UserDao {
     //此处省略代码
 } 
  Use @PostConstruct marked initialization method, using the methods of destruction marked @PreDestroy
@PostConstruct 
 public  void the init () { 
    System.out.println ( "initialization method ...." ); 
} 

@PreDestroy 
public  void the destroy () { 
    System.out.println ( "Method of destruction ....." ); 
}

  1.2 Spring new comment

  By the above configuration reduces Bean annotation in the xml configuration, annotation through simplified, reduced configuration. But it can not replace all of the following:

Loading a configuration file 
context: property-placeholder
component scans context: component-scan

  With the deepening of technology, most of the introduction of the new notes, fully replaced by new XML configuration annotations. The following new annotation:

Description annotation 
@Configuration specifies the current class is a class Spring configuration, when the loaded container is created from the class annotation 
@ComponentScan Spring for specifying at initialization package to scan the container. Spring action and in the xml configuration file < context: Scan-Component Base-Package = "com.itheima" /> as 
@Bean used in the method are denoted by the return value is stored in the Spring container 
@PropertySource with to load the configuration file .properties 
@Import other configurations for introducing classes

  The following are examples of the new annotation:

@Configuration 
@ComponentScan("com.itheima")
@Import({DataSourceConfiguration.class}) public class SpringConfiguration { }
@PropertySource("classpath:jdbc.properties") 
public class DataSourceConfiguration { 
  @Value("${jdbc.driver}") 
  private String driver; 
  @Value(
"${jdbc.url}")   private String url;
  @Value(
"${jdbc.username}")   private String username;
     @Value(
"${jdbc.password}")   private String password;   @Bean(name="dataSource")   public DataSource getDataSource() throws PropertyVetoException {
    ComboPooledDataSource dataSource = new ComboPooledDataSource();     dataSource.setDriverClass(driver);
    dataSource.setJdbcUrl(url);
    dataSource.setUser(username);
    dataSource.setPassword(password);
    return dataSource;
  }
}

  Test code:

@Test 
public void testAnnoConfiguration() throws Exception {
   // notes the need for new vessels acquired by this way applicationContext
  ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);  
  UserService userService = (UserService) applicationContext.getBean("userService");
  userService.save();
  DataSource dataSource = (DataSource) applicationContext.getBean("dataSource");
  Connection connection = dataSource.getConnection();
  System.out.println(connection);
}

Two, Spring integration Junit

  2.1 Original Spring Junit test questions

  In the test class, each test method has the following two lines of code:
AC = ApplicationContext new new ClassPathXmlApplicationContext ( "bean.xml"); // regardless of class or configuration profiles 
IAccountService ac.getBean AS = (. "The AccountService", IAccountService class );

  These two lines of action is to obtain a container, if you do not write it, you will be prompted direct null pointer exception. So it can not be easily deleted. This is very troublesome during the tests. Spring Integration junit can help us solve this problem.

  2.2 spring integrating junit

  Let SpringJunit responsible for creating Spring container, but you need to tell the name of the profile will need to be tested Bean were directly injected in the test class.

  Integration steps: 

  ① introducing coordinates of spring integration Junit
  ② replace the original run of annotations using @Runwith
  ③ using @ContextConfifiguration specified configuration file or configuration class
  ④ use @Autowired implants require test object
  ⑤ Create a test method for testing
  as follows:
  Import coordinates coordinates of introducing spring integration Junit
<! - here it should be noted that, spring5 and above requirements must be junit version 4.12 and above ->  
< dependency >
  < groupId > org.springframework </ groupId >
  < artifactId > the Spring-the Test </ artifactId >
  < Version > 5.0.2.RELEASE </ Version >
</ dependency >

< dependency >
  < the groupId > JUnit </ the groupId >
  < the artifactId > JUnit </artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency
  ② replace the original run of annotations using @Runwith
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringJunitTest {
}
  ③ using @ContextConfifiguration specified configuration file or configuration class
@RunWith (. The SpringJUnit4ClassRunner class ) 
// load the spring core profile //
@ContextConfiguration (value = { "CLASSPATH: the applicationContext.xml"}) // can choose one vertically
// load spring core configuration class
@ContextConfiguration (classes = SpringConfiguration {. class })
public class SpringJunitTest {}

  ④ use @Autowired implants require test object

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest { @Autowired private UserService userService; }
  ⑤ Create a test method for testing
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest { 

    @Autowired 
    private UserService userService; 

    @Test 
    public void testUserService(){ 
        userService.save(); 
    } 
}    

 

 

Guess you like

Origin www.cnblogs.com/tashanzhishi/p/12012574.html