1.Spring configuration non-custom object
1.1 Configuration method
Non-custom objects and non-custom objects are objects for Spring, so there is no difference in configuration.
Below, take the C3P0 data source (C3P0 connection pool) as an example to demonstrate Spring's configuration of "non-custom objects"
Development steps
①The coordinates of the imported data source and the database drive coordinates
② Create a data source object
③ Set the basic connection data of the data source
④Use the data source to obtain connection resources and return connection resources
1.2 Preparation
1.2.1 Import c3p0 connection pool coordinates
<!-- C3P0连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
1.2.2 Import mysql database drive coordinates
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
1.3 Create a data source
1.3.1 Manually create 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);
}
1.3.2 Spring configuration C3P0 connection pool (important)
<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>
1.4 Optimize Spring configuration (extract configuration file)
1.4.1 Extract jdbc.properties configuration file
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
1.4.2 Introduce the configuration file in the Spring configuration file
Note: This configuration requires that the corresponding namespace constraints must be introduced in Spring **context**。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--引入classpath路径下的jdbc.properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
</beans>
1.4.3 Modify the configuration of dataSource
<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.4.4 Summary
Spring container loads properties file
<context:property-placeholder location="xx.properties"/>
<property name="" value="${key}"/>
2. Spring annotation development
2.1 Overview of Spring
Spring is a light code and reconfiguration framework. The configuration is relatively heavy and affects development efficiency. Therefore, annotation development is a trend. Annotation instead of xml configuration files can simplify configuration and improve development efficiency.
2.1 Spring original annotations
Spring's original annotations are mainly alternative tag configurations
2.1.1 Annotations for creating objects
annotation | Explanation |
---|---|
@Component | Used on the class to instantiate Bean |
@Controller | Used on web layer class to instantiate Bean |
@Service | Used on service layer class to instantiate Bean |
@Repository | Used on dao layer class to instantiate Bean |
Case:
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Override
public void save() {
System.out.println("save running... ...");
}
}
//上述四个注解作用一样,也就是说,这里同样可以写其他三个注解,但约定俗成,Dao层一般使用Repository
2.1.2 Annotations for dependency injection
annotation | Explanation |
---|---|
@Autowired | Dependency injection based on type, if multiple are found, then dependency injection based on variable name |
@Qualifier | Used with @Autowired for dependency injection based on name |
@Resource | Equivalent to @ Autowired + @ Qualifier, injected according to the name |
@Value | Inject common attributes. Generally used to get the key in properties, and then injected into member variables |
Case:
Use @Autowired to inject reference types
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired //根据类型依赖注入,如果找到多个,则根据变量名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}") //获取已经加载到容器中的properties中的指定的键,并注入
private String driver;
@Override
public void save() {
System.out.println(str);
System.out.println(driver);
}
}
2.1.3 Annotation of scope of action
annotation | Explanation |
---|---|
@Scope | Two values: "prototype"-> multiple cases, "singleton"-> single case (default) |
Case:
@Scope("singleton")
public class UserDaoImpl implements UserDao {
//此处省略代码
}
2.1.4 Other notes
annotation | Explanation |
---|---|
@PostConstruct | The marked method is executed when the object is created |
@PreDestroy | The marked method is executed when the object is destroyed |
Case:
@PostConstruct
public void init(){
System.out.println("初始化方法....在对象被创建的时候执行....");
}
@PreDestroy
public void destroy(){
System.out.println("销毁方法....在对象被销毁的时候执行....");
}
2.1.4 Notes
When Spring uses annotations to develop, it is necessary to configure component scanning in applicationContext.xml. The role is to specify which package and the Beans under its sub-packages need to be scanned to identify the classes, fields, and methods configured using annotations.
<!--注解的组件扫描-->
<context:component-scan base-package="com.ittest"></context:component-scan>
3 New Spring Notes
3.1 Overview of new annotations
Spring's so-called new annotations are used to completely replace Spring's configuration files.
3.2 New annotation composition
annotation | Explanation |
---|---|
@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 package that Spring will scan when initializing the container. |
@Bean | Used in methods, mark the return value of the method stored in the Spring container |
@PropertySource | Used to load the configuration in the .properties file |
@Import | Used to import other configuration classes |
3.2 Detailed explanation of new annotations
3.2.1 @Configuration
Indicates that this class is a Spring configuration class, used to store spring configuration information
@Configuration
public class SpringConfiguration {
}
3.2.2 @ComponentScan
Used to specify the package that Spring will scan when initializing the container.
Equivalent to xml configuration
<context:component-scan base-package="com.ittest"/>
@Configuration
@ComponentScan("com.ittest")
public class SpringConfiguration {
}
3.2.3 @Import
Used to import other configuration classes
Equivalent to xml configuration
<import resource="classpath:applicationContext-dao.xml"/>
@Configuration
@ComponentScan("com.ittest")
@Import({DataSourceConfiguration.class})
public class SpringConfiguration {
}
3.2.4 @PropertySource
Used for properties configuration file
Equivalent to xml configuration
<context:property-placeholder location="classpath:jdbc.properties"/>
@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;
}
3.2.5 @Bean
Used in the method, Spring will automatically execute the method, and store the object returned by the method in the spring container
@Bean("dataSource")
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
}
3.2.5 Test new annotations (configuration class)
@Test
public void testAnnoConfiguration() throws Exception {
//根据配置类SpringConfiguration.class,获取Spring的核心容器
ApplicationContext ac =
new AnnotationConfigApplicationContext(SpringConfiguration.class);
//获取userService对象
UserService userService = (UserService)ac.getBean("userService");
userService.save();
//获取dataSource对象
DataSource dataSource = (DataSource)ac.getBean("dataSource");
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
3. Spring integrates Junit
3.1 Overview
In the original code, dependency injection cannot be used normally in the test class.
If you want to use dependency injection in the test class, you need to integrate Junit with Spring
3.2 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 to test
3.3 Spring integrated Junit code implementation
①Import the coordinates of spring integrated Junit
<!--此处需要注意的是,
spring5 及以上版本要求 junit 的版本必须是 4.12 及以上
scope:设置为test,就只能在test中执行-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.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 to test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
@Test
public void testUserService(){
userService.save();
}
}