Spring02—SpringIoC and DI annotation development

1. Spring configuration data source

1.1 The role of the data source (connection pool)

The data source (connection pool) is to improve the performance of the program as it appears

Instantiate the data source in advance and initialize some connection resources

Obtain from the data source when using connection resources

Return the connection resource to the data source after use

Common data sources (connection pool): DBCP, C3P0, BoneCP, Druid, etc.

Development steps

①Import the coordinates of the data source and the database-driven coordinates

②Create a data source object

③Set the basic connection data of the data source

④Use data sources to obtain connection resources and return connection resources

1.2 Manual creation of data source

①Import the coordinates of c3p0 and druid

<!-- C3P0连接池 -->
<dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
</dependency>
<!-- Druid连接池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>

①Import mysql database drive coordinates

<!-- mysql驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>

②Create a C3P0 connection pool

@Test
public void testC3P0() throws Exception {
    
    
	//创建数据源
	ComboPooledDataSource dataSource = new ComboPooledDataSource();
	//设置数据库连接参数
    dataSource.setDriverClass("com.mysql.jdbc.Driver");    	               	               dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
    dataSource.setUser("root");
    dataSource.setPassword("root");
	//获得连接对象
	Connection connection = dataSource.getConnection();
	System.out.println(connection);
}

②Create a Druid connection pool

@Test
public void testDruid() throws Exception {
    
    
    //创建数据源
    DruidDataSource dataSource = new DruidDataSource();
    //设置数据库连接参数
    dataSource.setDriverClassName("com.mysql.jdbc.Driver"); 
    dataSource.setUrl("jdbc:mysql://localhost:3306/test");   
    dataSource.setUsername("root");
    dataSource.setPassword("root");
    //获得连接对象
    Connection connection = dataSource.getConnection();    
    System.out.println(connection);
}

③Extract the jdbc.properties configuration file

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

④Read the jdbc.properties configuration file to create a connection pool

@Test
public void testC3P0ByProperties() throws Exception {
    
    
    //加载类路径下的jdbc.properties
    ResourceBundle rb = ResourceBundle.getBundle("jdbc");
    ComboPooledDataSource dataSource = new ComboPooledDataSource(); 
    dataSource.setDriverClass(rb.getString("jdbc.driver"));   
    dataSource.setJdbcUrl(rb.getString("jdbc.url")); 
    dataSource.setUser(rb.getString("jdbc.username")); 
    dataSource.setPassword(rb.getString("jdbc.password"));
    Connection connection = dataSource.getConnection();   
    System.out.println(connection);
}

1.3 Spring configuration data source

The creation of DataSource can be handed over to the Spring container to complete

DataSource has a parameterless construction method, and Spring defaults to instantiate objects through a parameterless construction method

To use DataSource, you need to set the database connection information through the set method, and Spring can perform string injection through the set method

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
    <property name="user" value="root"/>
    <property name="password" value="root"/>
</bean>

Test to get the data source from the container

ApplicationContext applicationContext = new 
           ClassPathXmlApplicationContext("applicationContext.xml");
               DataSource dataSource = (DataSource) 
applicationContext.getBean("dataSource");
Connection connection = dataSource.getConnection();
System.out.println(connection);

1.4 Extract the jdbc configuration file

applicationContext.xml loads the jdbc.properties configuration file to obtain connection information.

First, you need to introduce the context namespace and constraint path:

Namespace: xmlns:context="http://www.springframework.org/schema/context"

Constrained path: http: //www.springframework.org/schema/context

​ http://www.springframework.org/schema/context/spring-context.xsd

<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

1.5 Knowledge points

Spring container loads properties file

<context:property-placeholder location="xx.properties"/>
<property name="" value="${key}"/>

2. Spring annotation development

2.1 Spring original annotations

Spring is a light-code and re-configuration framework. The configuration is relatively heavy and affects development efficiency. Therefore, annotation development is a trend. Annotations can replace xml configuration files to simplify configuration and improve development efficiency.

Spring original annotations are mainly alternative configurations

annotation Description
@Component Used on the class to instantiate Bean
@Controller Used on the web layer class to instantiate Bean
@Service Used on the service layer class to instantiate Bean
@Repository Used on the dao layer class to instantiate Bean
@Autowired Used on fields for dependency injection based on type
@Qualifier Used in conjunction with @Autowired for dependency injection based on name
@Resource Equivalent to @Autowired+@Qualifier, inject according to the name
@Value Inject common attributes
@Scope Mark the scope of Bean
@PostConstruct Use to mark the method on the method as the initialization method of Bean
@PreDestroy Use the method to mark the method as the destruction method of Bean

note:

When using annotations for development, you need to configure component scanning in applicationContext.xml. The role is to specify which package and its subpackages Beans need to be scanned in order to identify the classes, fields, and methods configured with annotations.

<!--注解的组件扫描-->
<context:component-scan base-package="com.itheima"></context:component-scan>

Using @Compont or @Repository to identify UserDaoImpl requires Spring to instantiate.

//@Component("userDao")
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    
    
    @Override
    public void save() {
    
    
    	System.out.println("save running... ...");
    }
}

Using @Compont or @Service to identify UserServiceImpl requires Spring to instantiate

Use @Autowired or @Autowired+@Qulifier or @Resource for userDao injection

//@Component("userService")
@Service("userService")
public class UserServiceImpl implements UserService {
    
    
    /*@Autowired
    @Qualifier("userDao")*/
    @Resource(name="userDao")
    private UserDao userDao;
    @Override
    public void save() {
    
           
   	  userDao.save();
    }
}

Use @Value for string injection

@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 to mark the scope of the Bean

//@Scope("prototype")
@Scope("singleton")
public class UserDaoImpl implements UserDao {
    
    
   //此处省略代码
}

Use @PostConstruct to annotate the initialization method and @PreDestroy to annotate the destruction method

@PostConstruct
public void init(){
    
    
	System.out.println("初始化方法....");
}
@PreDestroy
public void destroy(){
    
    
	System.out.println("销毁方法.....");
}

2.2 Spring new annotations

Using the above annotations can not completely replace the xml configuration file, and the configuration that needs to be replaced by annotations is as follows:

Configuration of non-custom Bean:

Load the configuration of the properties file: context:property-placeholder

Configuration of component scan: context:component-scan

Introduce other files:

annotation Description
@Configuration Used to specify that the current class is a Spring configuration class, and annotations will be loaded from this class when the container is created
@ComponentScan Used to specify the packages that Spring will scan when initializing the container. The effect is the same as <context:component-scan base-package="com.itheima"/> in Spring's xml configuration file
@Bean Used on the method, annotate the return value of the method to be stored in the Spring container
@PropertySource Used to load the configuration in the .properties file
@Import Used to import other configuration classes

@Configuration

@ComponentScan

@Import

@Configuration
@ComponentScan("com.itheima")
@Import({
    
    DataSourceConfiguration.class})
public class SpringConfiguration {
    
    
}

@PropertySource

@value

@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

@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 load core configuration class to create Spring container

@Test
public void testAnnoConfiguration() throws Exception {
    
    
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);
    }

3. Spring integrates Junit

3.1 Problems with the original Junit test Spring

In the test class, each test method has the following two lines of code:

 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
 IAccountService as = ac.getBean("accountService",IAccountService.class);

The function of these two lines of code is to get the container. If you don't write it, it will directly prompt a null pointer exception. So it cannot be deleted easily.

3.2 Ideas for solving the above problems

Let SpringJunit be responsible for creating the Spring container, but you need to tell it the name of the configuration file

Will need to test Bean directly in the test class for injection

3.3 Spring integration Junit steps

①Import the coordinates of spring integrated Junit

② Use @Runwith annotation to replace the original runtime

③Use @ContextConfiguration to specify the configuration file or configuration class

④ Use @Autowired to inject the object to be tested

⑤Create a test method for testing

3.4 Spring integrated Junit code implementation

①Import the coordinates of spring integrated Junit

<!--此处需要注意的是,spring5 及以上版本要求 junit 的版本必须是 4.12 及以上-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.0.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

② Use @Runwith annotation to replace the original runtime

@RunWith(SpringJUnit4ClassRunner.class)
public class SpringJunitTest {
    
    
}

③Use @ContextConfiguration to specify the configuration file or configuration class

@RunWith(SpringJUnit4ClassRunner.class)
//加载spring核心配置文件
//@ContextConfiguration(value = {"classpath:applicationContext.xml"})
//加载spring核心配置类
@ContextConfiguration(classes = {
    
    SpringConfiguration.class})
public class SpringJunitTest {
    
    
}

④ Use @Autowired to inject the object to be tested

@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();
    }
}

Spring integration Junit steps

①Import the coordinates of spring integrated Junit

② Use @Runwith annotation to replace the original runtime

③Use @ContextConfiguration to specify the configuration file or configuration class

④ Use @Autowired to inject the object to be tested

⑤Create a test method for testing

Guess you like

Origin blog.csdn.net/yeyuweihuang/article/details/114433625