Spring框架学习的第三天(SpringIOC注解开发和SpringDI注解开发_Spring注解开发操作数据库完成增删改查)

为君一笑 提交于 2020-03-10 04:04:22

一、SpringIOC注解开发

1.pom.xml导入依赖

<!--Spring依赖-->
<dependencies>
    <!--spring核心依赖-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
</dependencies>

2.@Component注解替代bean标签完成SpringIOC中对象的配置


3.在实际项目开发时使用的是Component衍生的注解,Spring中提供了与Component等效的三个注解:@Service @Controller @Repository

3.1 解决Component注解可读性不高的问题:web层使用Controller注解、service层使用Service注解、在dao层使用Repository注解
3.2 如果某个类不明确属于某一层的时候使用Component注解,例如工具类
3.3 Component注解可以指定bean的名称,也可以不指定,如果不指定默认名称是类名首字母小写

4.bean标签中scope属性,init-method,destroy-method属性的注解替代

二、SpringDI注解开发

1.pom.xml导入依赖

<!--Spring依赖-->
<dependencies>
    <!--spring核心依赖-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
</dependencies>

2.不需要写构造函数,也不需要写set方法,而是第三种注入的方式:注解注入

2.1 实际开发过程中由于@Resource注解,它通过名称进行注入,一般不使用此注解,并不是spring框架的注解,而是java规范的注解,而且此注解和JDK相关,此注解在JDK9之后不能直接使用,不推荐使用
2.2 Autowired注解默认是根据类型进行的注入(不是根据名称进行的注入),会在spring容器里面会找到注解下的对象UserDaoImpl
2.3 假如有两个UserDao的实现类,而Autowired注解默认是根据类型进行的注入,它找的是哪个接口的实现类对象呢??
    /*1.根据属性类型到Spring容器中查找指定类型的对象,如果只能找到唯一的一个此类型的对象,那么它会直接把这个类型的对象赋值给要注入的属性*/
    /*2.如果没有找到任何对象和此类型匹配,它会直接失败*/
    /*3.如果找到了多个此类型对象,此时会根据注入的属性名称进行匹配,如果有和变量名称匹配的就把此对象注入给属性,如果变量名称和所有对象名称不匹配,那么会报错*/
    /*一般@Autowired会结合@Qualifier注解一起使用,它可以指定名称进行注入*/

三、Spring注解开发操作数据库完成增删改查

1.pom.xml导入依赖

<!--Spring依赖-->
<dependencies>
    <!--spring核心依赖-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
    <!--JdbcTemplate-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.2.4.RELEASE</version>
    </dependency>
    <!--连接池的依赖-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.26</version>
    </dependency>
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.2.4.RELEASE</version>
        <scope>test</scope>
    </dependency>
</dependencies>

2.在资源文件resource中创建如下的配置文件

beans.xml

<?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 https://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.bianyiit.service,com.bianyiit.dao,com.bianyiit.domain"></context:component-scan>
    <!--随着项目的增大,配置文件需要配置的内容肯定会增大,支持配置文件拆分,通过import引入-->
    <!--主配置文件只需要引入子配置文件的内容-->
    <import resource="spring-dao.xml"></import>
    <import resource="spring-datasource.xml"></import>
</beans>

spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--spring创建jdbcTemplate对象-->
    <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
    </bean>
</beans>

spring-datasource.xml

<?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 https://www.springframework.org/schema/context/spring-context.xsd">
    <!--加载外部属性文件jdbc.properties-->
    <context:property-placeholder location="jdbc.properties"></context:property-placeholder>

    <!--spring创建连接池对象,连接池对象只会被创建一次-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
</beans>

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/login
jdbc.user=root
jdbc.password=123

3.分别创建Service接口和实现类,domian实体类,dao接口和实现类

package com.bianyiit.service;

import com.bianyiit.domain.User;

import java.util.List;

public interface UserService {
    void addUser(User user);
    void deleteUser(Integer id);
    void update(User user);
    List<User> findAll();
}
package com.bianyiit.service.impl;

import com.bianyiit.dao.UserDao;
import com.bianyiit.domain.User;
import com.bianyiit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    @Qualifier("userDaoImpl")
    private UserDao userDao;

    @Override
    public void addUser(User user) {
        userDao.addUser(user);
    }

    @Override
    public void deleteUser(Integer id) {
        userDao.deleteUser(id);
    }

    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public List<User> findAll() {
        List<User> userList = userDao.findAll();
        return userList;
    }
}
package com.bianyiit.domain;

import lombok.Data;
import org.springframework.stereotype.Component;

@Component
@Data
public class User {
    private int id;
    private String username;
    private String password;
    private String sex;
    private String birthday;
    private String email;
}
package com.bianyiit.dao;

import com.bianyiit.domain.User;

import java.util.List;

public interface UserDao {
    void addUser(User user);
    void deleteUser(Integer id);
    void update(User user);
    List<User> findAll();
}
package com.bianyiit.dao.impl;

import com.bianyiit.dao.UserDao;
import com.bianyiit.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate template;

    @Override
    public void addUser(User user) {
        String sql="insert into usermsg values (null,?,?,?,?,?)";
        template.update(sql, user.getUsername(), user.getPassword(), user.getSex(), user.getBirthday(), user.getEmail());
    }

    @Override
    public void deleteUser(Integer id) {
        String sql="delete from usermsg where id=?";
        template.update(sql,id);
    }

    @Override
    public void update(User user) {
        String sql=" update usermsg set username=?,password=?,sex=?,birthday=?,email=? where id=?";
        template.update(sql,user.getUsername(),user.getPassword(),user.getSex(),user.getBirthday(),user.getEmail(),user.getId());
    }

    @Override
    public List<User> findAll() {
        String sql="select * from usermsg";
        List<User> userList = template.query(sql, new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }
}

4.在test测试包下创建UserServlet来模拟web层调用service层,service层调用dao层,只不过创建对象全部由Spring注解来帮我们创建

package com.bianyiit.test;

import com.bianyiit.domain.User;
import com.bianyiit.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/*解决Test测试类中无法使用@Autowired的办法*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:beans.xml")
public class UserServlet {

    @Autowired
    private User user;

    @Test
    public void testAddUser(){
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = applicationContext.getBean("userServiceImpl", UserService.class);
        user.setUsername("zs");
        user.setSex("男");
        user.setBirthday("1997-1-2");
        userService.addUser(user);
    }
    @Test
    public void testDeleteUser(){
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = applicationContext.getBean("userServiceImpl", UserService.class);
        userService.deleteUser(28);
    }
    @Test
    public void testUpdate(){
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = applicationContext.getBean("userServiceImpl", UserService.class);
        user.setId(1);
        user.setUsername("ls");
        user.setSex("女");
        userService.update(user);
    }
    @Test
    public void testFindAll(){
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = applicationContext.getBean("userServiceImpl", UserService.class);
        List<User> userList = userService.findAll();
        for (User user : userList) {
            System.out.println(user);
        }
    }
}

5.测试增删改查操作是否可行


添加用户操作成功

删除刚添加的用户操作成功

修改id为1的用户操作成功

查询所有用户操作成功

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!