preface

Two days ago, when I was having dinner with one of my classmates, my classmate told me that a person who had worked for two years in his company asked for a salary increase. He asked a question about Spring dependency injection, and the student who asked for a salary increase was completely confused. Later I went home and thought about this piece is really a little difficult, so I wrote an article to share with you what I know and what I sorted out online. At least you can answer when asked about this piece, and you won’t get a salary increase because of it. Without further ado, full of dry goods are below!

1. What is Spring’s dependency injection?

Dependency injection, an aspect of IOC, is a common concept that has multiple interpretations. The idea is that instead of creating an object, you just describe how it was created. You don’t assemble your components and services directly in code, but describe which components require which services in the configuration file, and then a container (IOC container) takes care of assembling them.

2. The role of IOC

Reduce the coupling between programs (dependency) Dependency management: In the future, spring will take care of the maintenance of objects that need to be used by other classes in the current class, provided by Spring. We only need to explain dependency maintenance in the configuration file, which is called dependency injection.

3. Several ways of Spring dependency injection

Data that can be injected: There are three types

Basic types and Strings. Other bean types (configured beans in configuration files or annotations). Complex type/collection type. Injection methods: There are three

Provided using the constructor. Provided using the set method. Provided using annotations.

Constructor injection

As the name suggests, it assigns values to member variables using constructors in a class. Note that we don’t do the assignment ourselves, but configure it and let the Spring framework inject it for us. The specific code is as follows:

<! Constructor injection: the tag to use :constructor-arg Where the tag appears: an attribute inside the bean tagtype: Specifies the data type of the data to be injected, which is also the type of one or more parameters in the constructor index: Specifies the data to be injected to assign values to the parameters in the constructor at the specified index position. The location of the index starts name: 0 is used to specify the parameter to the constructor is specified in the name of = = = = = = = = = = = = = = = = the above three is used to specify the parameter to the constructor which = = = = = = = = = = = = = = = = = = = value: Used to provide basic and String data ref: Used to specify other bean type data. It refers to the advantages of bean objects that have been present in Spring's Ioc core container: injecting data is a must when retrieving a bean object, otherwise the object cannot be created. Disadvantages: Changes the way bean objects are instantiated so that when we create objects, we have to provide the data if we don't need it. --> <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
    <constructor-arg name="name" value="Tester"></constructor-arg>
    <constructor-arg name="age" value="18"></constructor-arg>
    <constructor-arg name="birthday" ref="now"></constructor-arg> </bean> <! -- Configure a date object --> <bean id="now" class="java.util.Date"></bean>
Copy the code

Set injection

As the name suggests, provide a set method in a class that requires a member to be injected. The specific code is as follows:

<! --setMethod injection --> Tags involved in the more common way: Property where it appears: The property of the bean's internal tag Name: specifies what is invoked when injectedsetMethod name value: used to provide data of both primitive and String types ref: used to specify other bean types. It refers to the advantages of bean objects in Spring's Ioc core container: there are no clear restrictions on creating objects and the default constructor can be used directly. Disadvantage: it is possible to get objects if a member must have a valuesetMethod not executed. --> <bean id="accountService2" class="com.itheima.service.impl.AccountServiceImpl2">
    <property name="name" value="tom" ></property>
    <property name="age" value="23"></property>
    <property name="birthday" ref="now"></property>
</bean>
Copy the code

Collective injection

As the name implies, it is used to pass values to the members of the class in the set method injection, but the variable data type is set. Here we introduce injecting arrays, lists, sets, maps, Properties.

Injection of complex types/injection of collection types

Tags for injecting a List of props: List, array, set Tags for injecting a Map of props: Map, props

The code is as follows:

The User class

public class User {
    private String name;
    private Integer age;
    private Date birth;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public User(){
        System.out.println("I was created...");
    }
    public void show(){
        System.out.println("The show method in user calls...");
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' + ", age=" + age + ", birth=" + birth + '}'; }}Copy the code

The Person class

public class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' + ", age=" + age + '}'; }}Copy the code

CollectionDemo class

public class CollectionDemo {
    private String[] arr;
    private List<String> myList;
    private Set<String> mySet;
    private Map<String,String> myMap;
    private Properties myProp;

    public void setArr(String[] arr) {
        this.arr = arr;
    }

    public void setMyList(List<String> myList) {
        this.myList = myList;
    }

    public void setMySet(Set<String> mySet) {
        this.mySet = mySet;
    }

    public void setMyMap(Map<String, String> myMap) {
        this.myMap = myMap;
    }

    public void setMyProp(Properties myProp) {
        this.myProp = myProp;
    }

    public String[] getArr() {
        return arr;
    }

    public List<String> getMyList() {
        return myList;
    }

    public Set<String> getMySet() {
        return mySet;
    }

    public Map<String, String> getMyMap() {
        return myMap;
    }

    public Properties getMyProp() {
        returnmyProp; }}Copy the code

Configuration file:

<! Assemble beans based on XML form --> <bean id="user" class="com.atguigu.java1.User"></bean> <! Create a bean using the get method --> <bean id="user2" class="com.atguigu.java1.User">
    <property name="name" value="Zhang"></property>
    <property name="age">
        <value>20</value>
    </property>
    <property name="birth" ref="now"></property>
</bean>
<bean id="now" class="java.util.Date"></bean> <! Dependency injection for collection and array types --> <bean id="demo" class="com.atguigu.java1.CollectionDemo">
    <property name="arr">
        <array>
            <value>111</value>
            <value>222</value>
            <value>333</value>
        </array>
    </property>
    <property name="myList">
        <list>
            <value>111</value>
            <value>222</value>
            <value>333</value>
        </list>
    </property>
    <property name="mySet">
        <set>
            <value>111</value>
            <value>222</value>
            <value>333</value>
        </set>
    </property>
    <property name="myMap">
        <map>
            <entry key="aaa" value="aaa"></entry>
            <entry key="bbb" value="bbb"></entry>
            <entry key="ccc" value="ccc"></entry>
        </map>
    </property>
    <property name="myProp">
        <props>
            <prop key="aaa">aaa</prop>
            <prop key="bbb">bbb</prop>
            <prop key="ccc">ccc</prop> </props> </property> </bean> <! Create bean with default constructor --> <bean id="person" class="com.atguigu.java1.Person">
    <constructor-arg name="name" value="Zhang Sanfeng"></constructor-arg>
    <constructor-arg name="age" value="18"></constructor-arg>
</bean>
Copy the code

The test class:

/** */ @test public voidtest3(){
    ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml");
    User user= (User) ioc.getBean("user"); // The interrupt point here verifies when the object was created. user.show(); } /** * create the bean object with the default constructor */ @test public voidtest(){
    ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml");
    Person p= (Person) ioc.getBean("person");
    Person p2= (Person) ioc.getBean("person"); System.out.println(p.toString()); } /** * use get method */ @test public voidtest4(){
    ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml");
    User user= (User) ioc.getBean("user2"); // The interrupt point here verifies when the object was created. System.out.println(user.toString()); } /** * dependency injection of collections and arrays */ @test public voidtest5(){
    ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml");
    CollectionDemo demo= (CollectionDemo) ioc.getBean("demo");
    System.out.println(Arrays.toString(demo.getArr()));
    System.out.println(demo.getMyList());
    System.out.println(demo.getMySet());
    System.out.println(demo.getMyMap());
    System.out.println(demo.getMyProp());
}
Copy the code

4. Use Spring’s IOC to implement CRUD for the account

4.1 Based on XML

1. Reference the external properties file

2. SPEL expression

Spring Expression Language Spring Expression Language (SpEL) Runtime queries are supported and object graphs can be manipulated. Like EL expressions on JSP pages and OGNL expressions used in Struts2, SpEL accesses the object graph based on properties defined by Javabean-style getXxx() and setXxx() methods, completely in line with familiar operation habits. 2. SpEL uses #{... } as the delimiter, all characters in the big box number will be considered SpEL expressions. <property name="frequency" value="#{89.7}"/> <property name="capacity" value="#{1e4}"/> ●String literals can be delimited by single or double quotation marks. Value = "# {' Chuck '}" / > < property name = "name" value = '# {} "Chuck" / > low Boolean: < property name = "enabled" value = "# {false}" / > 4. References to other beans < bean id = "emp04" class = "com. Atguigu. Parent. Bean. The Employee" > < property name = "empId" value = "1003" / > < property name="empName" value="jerry"/> <property name="age" value="21"/> <property name="detp" value="#{dept}"/> </bean> 5. Some references to other beans attribute values as their the value of the attribute < bean id = "emp05" class = "com. Atguigu. Parent. Bean. The Employee" > < property name = "empId" value = "1003" / > <property name="empName" value="jerry"/> <property name="age" value="21"/> <property name="deptName" value="#{dept.deptName}"/> </bean> 6. Calling a non-static method <! Create an object, Call the object method in SpEL expressions - > < bean id = "salaryGenerator" class = "com. Atguigu. SpEL. Beans. SalaryGenerator" / > < bean id = "employee" class="com.atguigu.spel.bean.Employee"> <! - by object method return values for the attribute assignment - > < property name = "salayOfYear" value = "# {salaryGenerator. GetSalaryOfYear (5000)}" / > < / bean > 7. Call the static method < bean id = "employee" class = "com. Atguigu. Spel. Bean. The employee" > <! <property name="circle" value="#{T(java.lang.math).pi *20}"/> </bean> 8. Operator (1) arithmetic operators: +, -, *, /, %, ^ (2) the string concatenation: + (3) comparison operators: <, >, = =, < =, > =, lt, gt, eq, le, ge (4) logical operators: and, or, not, | (5) the ternary operator: judgment conditions? Value when the result is true: value when the result is false ⑥ Regular expression: matchesCopy the code

The code is as follows:

The configuration file

<? 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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="Http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd 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-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
  
	<bean id="accountDao" class="com.atguigu.dao.impl.AccountDaoImpl">
		<property name="runner" ref="runner"></property>
	</bean>
	<bean id="accountService" class="com.atguigu.service.impl.AccountServiceImpl">
		<property name="accountDao" ref="accountDao"></property>
	</bean>
	<bean id="account" class="com.atguigu.domain.Account"></bean>
  
	<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
		<constructor-arg name="ds" ref="dataSource"></constructor-arg>
	</bean>
  
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
		<property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
		<property name="username" value="root"></property>
		<property name="password" value="123456"></property>
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	</bean>
</beans>
Copy the code

The persistence layer

/* Public class AccountDaoImpl implements IAccountDao {private QueryRunner runner; public voidsetRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountById(Integer accountId) {
        try{
            return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {
        try{
            runner.update("insert into account(name,money)values(? ,?) ",account.getName(),account.getMoney());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void updateAccount(Account account) {
        try{
            runner.update("update account set name=? ,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?",accountId); }catch (Exception e) { throw new RuntimeException(e); }}}Copy the code

The business layer

/* Public class AccountServiceImpl implements IAccountService{private IAccountDao accountDao; public voidsetAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findAccountById(Integer accountId) {
        returnaccountDao.findAccountById(accountId); } public void saveAccount(Account account) { accountDao.saveAccount(account); } public void updateAccount(Account account) { accountDao.updateAccount(account); } public void deleteAccount(Integer acccountId) { accountDao.deleteAccount(acccountId); }}Copy the code

The test class

public class Test1 {
    ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml");
    @Test
    public void test1(){
        IAccountService service= (IAccountService) ioc.getBean("accountService"); service.deleteAccount(2); }}Copy the code

4.2 Mash-up of XML and annotations

XML configuration form:

<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl" scope="" 
		init-method="" destroy-method="">
    <property name=""  value="" | ref=""></property>
</bean>
Copy the code

1. Used to create objects

They serve the same purpose as writing a tag in an XML configuration file.

Component: used to store the current class object in the Spring container property: value: Used to specify the bean ID. When we do not write, it defaults to the name of the current class with the first letter lowercase.

Controller: Generally used at the presentation level

Service: Generally used at the business layer

Repository: Typically used in the persistence layer

These annotations have exactly the same functions and attributes as Component. They are annotations that the Spring framework uses to provide us with unambiguous layers to make our layer objects clearer.

2. Used to inject data

They serve the same purpose as writing a label to a bean label in an XML configuration file.

Autowired: Function: Automatically inject according to type. Injection succeeds as long as the only bean object type in the container matches the type of the variable being injected. If no bean type in the IOC container matches the type of the variable being injected, an error is reported. If multiple types in an Ioc container match:

Occurrence location: can be on a variable, can be on a method.

Details: The SET method is not required when using annotation injection.

Qualifier: Function: Inject by name in addition to the injection in the class. Cannot be used alone when injecting class members. But it can when injecting method parameters.

Property: value: Used to specify the ID of the injected bean.

Resource: Uses the bean ID directly. It can stand alone.

Attribute: name: Specifies the id of the bean. All of the above injections can only inject data from other bean types, and primitive and String types cannot be implemented using the above annotations. In addition, injection of collection types can only be done through XML.

Value: Used to inject basic and String data.

Property: value: Used to specify the value of data. ${SpEL} ${SpEL}

3. Used to change the scope of action

They do the same thing you do with the Scope attribute in the bean tag.

Scope: Specifies the Scope of the bean.

Property: value: Specifies the value of a range. Common values: Singleton prototype

4. Lifecycle related (Understand)

They have the same effect as init-method and destroy-methode in bean tags.

PreDestroy Function: Specifies the destruction method. PostConstruct is used to specify the initialization method.

The code is as follows:

The configuration file

<? 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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="Http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd 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-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"> <! <context:component-scan base-package= --> <context:component-scan base-package="com.atguigu"></context:component-scan>
  
	<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
		<constructor-arg name="ds" ref="dataSource"></constructor-arg>
	</bean>
  
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
		<property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
		<property name="username" value="root"></property>
		<property name="password" value="123456"></property>
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	</bean>
</beans>
Copy the code

The persistence layer

/** * The persistence layer implementation class of the account */ @repository (value ="accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;

    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountById(Integer accountId) {
        try{
            return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {
        try{
            runner.update("insert into account(name,money)values(? ,?) ",account.getName(),account.getMoney());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void updateAccount(Account account) {
        try{
            runner.update("update account set name=? ,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?",accountId); }catch (Exception e) { throw new RuntimeException(e); }}}Copy the code

The business layer

/** ** @service ()"accountService")
public class AccountServiceImpl implements IAccountService{
    @Autowired
    private IAccountDao accountDao;

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findAccountById(Integer accountId) {
        returnaccountDao.findAccountById(accountId); } public void saveAccount(Account account) { accountDao.saveAccount(account); } public void updateAccount(Account account) { accountDao.updateAccount(account); } public void deleteAccount(Integer acccountId) { accountDao.deleteAccount(acccountId); }}Copy the code

The test class

public class AccountServiceTest {
    @Test
    public void testFindAll() {/ / 1. Get easy ApplicationContext ac = new ClassPathXmlApplicationContext ("bean.xml"); IAccountService as = ac.getBean("accountService",IAccountService.class); List<Account> accounts = as.findallAccount ();for(Account account : accounts){
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne() {/ / 1. Get easy ApplicationContext ac = new ClassPathXmlApplicationContext ("bean.xml"); IAccountService as = ac.getBean("accountService",IAccountService.class); Account Account = as.findAccountById(1); //3. System.out.println(account); } @Test public voidtestSave() {
        Account account = new Account();
        account.setName("test"); account.setMoney(12345f); / / 1. Get easy ApplicationContext ac = new ClassPathXmlApplicationContext ("bean.xml"); IAccountService as = ac.getBean("accountService",IAccountService.class); As.saveaccount (account); } @Test public voidtestUpdate() {/ / 1. Get easy ApplicationContext ac = new ClassPathXmlApplicationContext ("bean.xml"); IAccountService as = ac.getBean("accountService",IAccountService.class); Account Account = as.findAccountById(4); //3. account.setMoney(23456f); as.updateAccount(account); } @Test public voidtestDelete() {/ / 1. Get easy ApplicationContext ac = new ClassPathXmlApplicationContext ("bean.xml"); IAccountService as = ac.getBean("accountService",IAccountService.class); //3. Execute method as.deleteAccount(4); }}Copy the code

4.3 Pure Annotation Configuration

1. The annotation

This class is a configuration class that does the same thing as bean.xml.

New notes in Spring:

Configuration:

Action: Specifies that the current class is a configuration class. Details: when the parameters of the configuration class as AnnotationConfigApplicationContext object creation, it can not write.

ComponentScan:

Purpose: Use an annotation to specify which packages spring will scan when creating the container.

Property: value: This serves the same purpose as basePackages, specifying which packages to scan when creating the container. Using this annotation is equivalent to configuring in XML:

<! <context:component-scan base-package= --> <context:component-scan base-package= --> <context:component-scan base-package= --> <context:component-scan base-package= --> <context:component-scan base-package="com.itheima"></context:component-scan>
Copy the code

Bean:

What it does: Stores the return value of the current method as a bean object into Spring’s IOC container.

Attribute: name: Specifies the id of the bean. When not written, the default value is the name of the current method.

Details: When we configure methods using annotations, the Spring framework will look for bean objects in the container that are not available if there are method parameters. The way the lookup is done is the same as the Autowired annotation.

Import: Used to Import other configuration classes.

Property: value: Used to specify the bytecode of another configuration class. When we use the Import annotation, the class of the Import annotation is the parent configuration class, and the imported classes are the child configuration classes

PropertySource:

Purpose: Specifies the location of the properties file.

Property: value: Specifies the name and path of the file. Keyword: classpath: indicates the classpath.

2. The takeup spring integration

Description: 1, the entrance of the application main method

Junit integrates a main method that determines which methods in the current Test class have the @test annotation. Junit lets the methods that have the Test annotation execute

Junit doesn’t care if we use the Spring framework or not. Junit doesn’t know if we use the Spring framework or not when we execute our test methods, so it doesn’t create a Spring core container for us to read configuration files/configuration classes.

4. It can be seen from the above three points that when the test method is executed, injection cannot be realized even if Autowired annotations are written without an Ioc container.

Unit test with Junit: Spring integrate Junit configuration: Test our configuration

2, using Junit provides an annotation have replaced the original main method, replacing the spring provided @ Runwith (SpringJUnit4ClassRunner. Class)

3, tell the Spring runner whether Spring and IOC creation is based on XML or annotations and specify the @contextConfiguration location

Parameter Description:

Locations: Specifies the location of the XML file, plus the classpath keyword, indicating that it is in the classpath. Classes: Specifies the location of the annotation class. Note: When using the Spring 5.x release, the junit jar must be 4.12 or higher.

The code is as follows:

The configuration class

/**
 * @author Guohai
 * @createTime 2020-07-13 17:14
 */
@Configuration
@ComponentScan("com.atguigu")
@Import(JdbcConfig.class)
@PropertySource("classpath:c3p0.properties")
public class SpringConfig {

}
Copy the code

Configure a subclass

/**
 * @author Guohai
 * @createTime 2020-07-13 17:16
 */
public class JdbcConfig {
    @Bean(name="runner")
    @Scope(value = "prototype")
    public QueryRunner getRunner(@Qualifier("ds1") DataSource dataSource) {
        QueryRunner runner = new QueryRunner(dataSource);
        return runner;
    }

    private static DataSource dataSource = null;

    @Bean(name="ds1")
    public DataSource getDataSource() {
        try {
            Properties prop = new Properties();
            InputStream is = JdbcConfig.class.getClassLoader().getResourceAsStream("jdbc.properties");
            prop.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(prop);
            return dataSource;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
  
    @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="ds2")
    public DataSource getDataSource2(){
        try {
            ComboPooledDataSource dataSource=new ComboPooledDataSource();
            dataSource.setDriverClass(driver);
            dataSource.setJdbcUrl(url);
            dataSource.setUser(username);
            dataSource.setPassword(password);
            return dataSource;
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        returnnull; }}Copy the code

The test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

    @Autowired
    private IAccountService as = null;

    @Test
    public void testFindAllList<Account> accounts = as.findallAccount ();for(Account account : accounts){
            System.out.println(account);
        }
    }

    @Test
    public void testFindOneAccount Account = as.findAccountById(1); System.out.println(account); } @Test public voidtestSave() {
        Account account = new Account();
        account.setName("test anno"); account.setMoney(12345f); As.saveaccount (account); } @Test public voidtestUpdate() {//3. Account Account = as.findAccountById(4); account.setMoney(23456f); as.updateAccount(account); } @Test public voidtestDelete() {//3. Execute method as.deleteAccount(4); }}Copy the code

5. Automatic assembly of Spring

In Spring, objects don’t have to find or create other objects associated with them. The container assigns references to objects that need to cooperate with each other, and Autowire is used to configure the auto-load mode.

There are five types of autowiring in the Spring framework XML configuration: (1) No: the default method is not autowiring, and the bean is assembled by manually setting the ref attribute. (2) byName: Automatic assembly is carried out by bean name. If the property of a bean is the same as the name of another bean, automatic assembly is carried out. (3) byType: automatic assembly is carried out by the data type of the parameter. (4) constructor: constructor is used for assembly, and constructor parameters are assembled by byType. (5) Autodetect: automatic detection. If there is a constructor, automatic assembly should be carried out through construct; otherwise, automatic assembly should be carried out through byType.

The last

You can leave a comment below to discuss what you don’t understand. You can also pay attention to my private letter and ask me. I will answer it after I see it. Also welcome everyone to pay attention to my official account: bright future, Golden Three silver four job-hunting interview season, sorted out more than 1000 nearly 500 pages of PDF documents of Java interview questions, articles will be updated in it, sorted out the information will be placed in it. Thank you for watching, think the article is helpful to you remember to pay attention to me a thumb-up support!!