Learning spring 2: ioc implemented based annotation and dependency injection + xml

Learning spring 2: ioc implemented based annotation and dependency injection + xml

First, open spring support for annotations in the spring 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: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">

    <!--基于注解+xml的spring配置-->
    <!-- 告知spring在创建容器时要扫描的包 -->
    <context:component-scan base-package="com.lyy"></context:component-scan>

</beans>

Second, using annotations to configure the bean to be created

In the spring needs to be set on the container corresponding to classes with the annotation, then the annotation can be used to configure bean, bean does not require the configuration file using the tag configuration.

@Component, @Controller, @Service, @Repository, These annotations added to the class, informed the spring to create an object class is put in a container.

Third, related to dependency injection annotations

3.1 inject a bean

autowired

Automatically according to the type of injection. When using annotation injection property, set method can be omitted. It can only be injected into other bean types. When there are multiple types of matches, to be injected using the object variable name as the bean id, find the container in the spring, you can also find a successful injection. Can not be found on the error

Qualifier

On the basis of the automatic injection according to the type of above, according to the Bean refilling id. It can not be used independently when a field injection, must be used with @Autowire; but when a parameter injection method, can be used independently.

Property: value, specifying the bean id

Resource

Direct injection according to Bean's id. It can only be injected into other bean types. Attribute: name, specify the bean id

3.2 Simple injection type (base + String)

Value

Injection basic data types and data type String. Attribute: value, for a specified value.

Fourth, Example: to achieve a crud operations on account

+ Xml annotation using spring configured to implement a crud operation on the account, persistence is achieved using commons-dbutils

3.1 Creating sql databases and tables

-- 创建数据库
CREATE DATABASE spring_demo1;
SHOW TABLES;
USE spring_demo1;
-- 创建账户表
CREATE TABLE account(
  id VARCHAR(64) PRIMARY KEY,
  `name` VARCHAR(32),
  money FLOAT
)

-- 新增记录
INSERT INTO account(id,`name`,money) VALUE(MD5(UUID()),'张三',100);

SELECT * FROM account 

3.2 maven dependence

<dependencies>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.16</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

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

        <!--数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.11</version>
        </dependency>

        <!--JDBC工具类库-->
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.6</version>
        </dependency>
    </dependencies>

3.3 spring configuration file

Open support for annotations in this configuration file, configure the connection pool of bean and bean QueryRunner

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 开启注解扫描,管理service和dao -->
    <context:component-scan base-package="com.lyy.service">
    </context:component-scan>
    <context:component-scan base-package="com.lyy.dao">

    </context:component-scan>

    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 配置连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--配置common-dbutils的核心对象-->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>
</beans>

Creating 3.4 entity class

import lombok.Data;

/**
 * 账户实体类
 */
@Data
public class Account {
    private String id;
    private String name;
    private float money;
}

3.5 Creating dao, the package structure and corresponding service implementation class

Wherein the following implementation class dao


@Repository(value = "accountDaoImpl2")
public class AccountDaoImpl2 implements IAccountDao {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private QueryRunner queryRunner;

    @Override
    public void insert(Account account) {
        try {
            String sql="INSERT INTO account(id,`name`,money) VALUE(MD5(UUID()),?,?)";
            Object[] params={account.getName(),account.getMoney()};
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("新增记录出错,e"+e.toString());
        }
    }

    @Override
    public List<Account> findAll() {
        try {
            String sql="SELECT * FROM account";
            List list = (List) queryRunner.query(sql, new BeanListHandler(Account.class));
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查询全部记录出错,e"+e.toString());
        }
    }

    @Override
    public Account findById(String id) {
        try {
            String sql="SELECT * FROM account WHERE id=?";
            Account account = queryRunner.query(sql, new BeanHandler<>(Account.class), id);
            return account;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查询指定记录出错,e"+e.toString());
        }
    }

    @Override
    public void delete(String id) {
        try {
            String sql="DELETE FROM account WHERE id=?";
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("删除指定记录出错,e"+e.toString());
        }
    }

}

Then achieve the object type used in injection Autowired service, the method will be called dao

    @Autowired
    @Qualifier(value = "accountDaoImpl2")
    private IAccountDao accountDao;

3.6 Test

To obtain the service object from the spring container, and performs the corresponding method

    @Test
    public void testFindAll(){
        ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
        IAccountService accountService = app.getBean(IAccountService.class);
        List<Account> list = accountService.findAll();
        System.out.println(Arrays.toString(list.toArray()));
    }

V. Summary

Notes xml configuration and configuration process is the same, are the first bean into a container, placed in the process may involve the issue of dependency injection, with the main use dependency injection annotations achieve two notes: @Autowired and @ Value

Example Project Address
Example Project address

Guess you like

Origin www.cnblogs.com/chengxuxiaoyuan/p/12154330.html