Spring(三:IOC案列演示---xml及注解)

一、基于XML

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>spring_ioc_xml</groupId>
    <artifactId>zte</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <!--spring依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>

        <!--mysql依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>

        <!--Dbutils依赖-->
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.6</version>
        </dependency>

        <!--c3p0依赖-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>
    </dependencies>

</project>

bean.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">

    <bean id = "studentServiceImpl" class="zte.com.business.service.StudentServiceImpl">
        <!--这里采用构造注入的方式-->
        <constructor-arg name="studentDao" ref = "studentDaoImpl"></constructor-arg>
    </bean>


    <bean id = "studentDaoImpl" class="zte.com.business.dao.StudentDaoImpl">
        <!--这里采用set方法注入的方式-->
        <property name="queryRunner" ref="runner"></property>
    </bean>


    <bean id = "runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--QueryRunner:带参构造,只能构造函数注入-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>

    <bean id = "dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--链接数据库的信息-->
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://10.5.16.76:3306/stu_db"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>

</beans>

dao层(接口忽略)

package zte.com.business.dao;

public class StudentDaoImpl implements IStudentDao{

    private QueryRunner queryRunner;

    public void setQueryRunner(QueryRunner queyRunner) {
        this.queryRunner = queryRunner;
    }

    public List<Student> findAllStudent() {
        try{
            List<Student> list = queryRunner.query("select * from student", new BeanListHandler<Student>(Student.class));
            return list;
        }catch (Exception e){
            throw new RuntimeException("查询所有学生信息失败");
        }
    }

    public Student findById(Integer studentId) {
        try{
            Student student = queryRunner.query("select * from student where id = ?", new BeanHandler<Student>(Student.class),studentId);
            return student;
        }catch (Exception e){
            throw new RuntimeException("查询单个学生信息失败");
        }
    }

    public void saveStudent(Student student) {
        try{
            queryRunner.update("insert into student (id,name) values (?,?)",student.getId(),student.getName());
        }catch (Exception e){
            throw new RuntimeException("添加单个学生信息失败");
        }
    }

    public void deleteById(Integer studentId) {
        try{
            queryRunner.update("delete from student where id = ?",studentId);
        }catch (Exception e){
            throw new RuntimeException("删除单个学生信息失败");
        }
    }
}

service层(接口忽略)

package zte.com.business.service;

public class StudentServiceImpl implements IStudentService {

    private IStudentDao studentDao;

    public StudentServiceImpl(IStudentDao studentDao) {
        this.studentDao = studentDao;
    }

    public List<Student> findAllStudent() {
        return studentDao.findAllStudent();
    }

    public Student findById(Integer studentId) {
        return studentDao.findById(studentId);
    }

    public void saveStudent(Student student) {
        studentDao.saveStudent(student);
    }

    public void deleteById(Integer studentId) {
        studentDao.deleteById(studentId);
    }
}

测试类: 写在test包下

package com.test;
public class StudentTest {

/**
 *  1. 应用程序的入口: main方法;
 *  2,单元测试中,虽然没有main方法,但是junit实际集成了一个main方法; 如果加上@Test,则就会集成到;
 *  3. junit根本不知道是否继承了spring框架,因此不会读取配置文件/配置类
 *    
 *    由此可得:junit无法读取到容器,必须手动来创建容器,进行测试
 */
    public static ApplicationContext ac;
    public static IStudentService studentServiceImpl;

    @Before
    public void init(){
        ac = new ClassPathXmlApplicationContext("bean.xml");
        studentServiceImpl = (IStudentService) ac.getBean("studentServiceImpl");
    }

    @Test
    public void find() {
        List<Student> list = studentServiceImpl.findAllStudent();
        System.out.println(list);
    }

    @Test
    public void findById() {
        Student student = studentServiceImpl.findById(2);
        System.out.println(student);
    }

    @Test
    public void deleteByid() {
        studentServiceImpl.deleteById(5);
    }

    @Test
    public void insertOne() {
        Student student = new Student();
        student.setId(5);
        student.setName("zhang");
        studentServiceImpl.saveStudent(student);
    }
}

二、基于注解(XML转化为注解)

其他类

  • service层,dao层代码根据之前经验修改即可,bean.xml删除;

jdbc.properties

driverClass=com.mysql.cj.jdbc.Driver
jdbcURL=jdbc:mysql://10.5.16.76:3306/stu_db
user=root
password=1234

副配置类

package zte.com.business.config;

/**1. 包扫描:必须先扫到带spring注解的类,再去扫描类中的其他注解
 * 2. 副配置类:
 *            1. 加@Configuration注解;
 *            2. 在创建AnnotationConfigApplicationContext时候,把该类也加上;
 *            3. 在主配置类中中加上
 * */
public class JDBCConfig {

    @Value("${driverClass}")
    private String driverClass;

    @Value("${jdbcURL}")
    private String jdbcURL;

    @Value("${user}")
    private String user;

    @Value("${password}")
    private String password;

    @Bean
    public DataSource getDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driverClass);
        dataSource.setJdbcUrl(jdbcURL);
        dataSource.setUser(user);
        dataSource.setPassword(password);
        return dataSource;
    }
}

主配置类

package zte.com.business.config;

import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
/** a. @Configuration
 *         1. 表明这个是一个配置类,作用和bean.xml一样
 *         2. AnnotationConfigApplicationContext对象创建时添上该类时候,可以不写该注解
 *
 *  b. @ComponentScan
 *         1. value属性和basepackage属性一样,值为数组,如果只有一个,则可以省略{}
 *
 *  c.@Import
 *         1. 加载其他的副配置类
 *
 *  d. @Bean
 *         1. 将方法的返回值存入到容器中,默认key为方法名;
 *         2. value和name属性作用一样;
 *         3. 如果方法有参数,spring会去容器中查找,功能和Autowired一样的
 *
 *  e. @PropertySource
 *        1. 配置文件的路径,value属性指定路径;
 *        2. 要加上classpath;
 */
@Configuration
@ComponentScan(basePackages = {"zte.com.business"})
@Import(JDBCConfig.class)
@PropertySource(value = "classpath:jdbc.properties")
public class IOCConfig {

    @Bean(value = "getQueryRunner")
    @Scope(value = "prototype")
    public QueryRunner getQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

}

测试类

  • 测试类中,service层的具体实现依然要用容器去手动去取,但dao层的具体实现就可以用自动注入的方式;
  • 因为junit测试并不知道当前测试是基于Spring的IOC,因此不可能注入service层的对象;
  • 因此引入下面的junit与spring的整合,从而就不用手动去容器中取对象;
package com.test;

public class StudentTest {

    public static ApplicationContext ac;
    public static IStudentService studentServiceImpl;

    @Before
    public void init(){
        // 需要更换具体的容器类,为Config的字节码文件
        ac = new AnnotationConfigApplicationContext(IOCConfig.class);
        studentServiceImpl = (IStudentService) ac.getBean("studentServiceImpl");
    }

    @Test
    public void findAll() {
        List<Student> list = studentServiceImpl.findAllStudent();
        System.out.println(list);
    }

    @Test
    public void findById() {
        Student student = studentServiceImpl.findById(2);
        System.out.println(student);
    }

    @Test
    public void deleteByid() {
        studentServiceImpl.deleteById(5);
    }

    @Test
    public void insertOne() {
        Student student = new Student();
        student.setId(5);
        student.setName("zhang");
        studentServiceImpl.saveStudent(student);
    }
}

三、junit整合spring

pom.xml依赖(spring整合junit)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>spring_ioc_xml</groupId>
    <artifactId>zte</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <!--spring依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>

        <!--mysql依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>

        <!--Dbutils依赖-->
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.6</version>
        </dependency>

        <!--c3p0依赖-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

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

        <!--spring整合junit, 5.2.6要求 junit是4.12及以上版本-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>
    </dependencies>

</project>

测试类

package com.test;

/**  1. 添加spring整合junit的pom依赖;
 *   2. 使用junit的一个注解,将junit的main方法替换成spring提供的main方法;
 *   3. 告知spring的运行器,sping的IOC容器是基于xml的还是基于注解的,并说明位置,
 *      spring提供的main方法,会去加载自动创建容器,不用手动创建;
 *      @ContextConfiguration
 *         locations : 指定xml的位置,加上classpath关键字
 * */

//@ContextConfiguration(locations = "classpath:bean.xml")
@ContextConfiguration(classes = IOCConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class StudentTest {

    @Autowired
    public  IStudentService studentServiceImpl;

    @Test
    public void findAll() {
        List<Student> list = studentServiceImpl.findAllStudent();
        System.out.println(list);
    }

    @Test
    public void findById() {
        Student student = studentServiceImpl.findById(2);
        System.out.println(student);
    }

    @Test
    public void deleteByid() {
        studentServiceImpl.deleteById(5);
    }

    @Test
    public void insertOne() {
        Student student = new Student();
        student.setId(5);
        student.setName("zhang");
        studentServiceImpl.saveStudent(student);
    }
}
深度学习是机器学习的一个子领域,它基于人工神经网络的研究,特别是利用多层次的神经网络来进行学习和模式识别。深度学习模型能够学习数据的高层次特征,这些特征对于图像和语音识别、自然语言处理、医学图像分析等应用至关重要。以下是深度学习的一些关键概念和组成部分: 1. **神经网络(Neural Networks)**:深度学习的基础是人工神经网络,它是由多个层组成的网络结构,包括输入层、隐藏层和输出层。每个层由多个神经元组成,神经元之间通过权重连接。 2. **前馈神经网络(Feedforward Neural Networks)**:这是最常见的神经网络类型,信息从输入层流向隐藏层,最终到达输出层。 3. **卷积神经网络(Convolutional Neural Networks, CNNs)**:这种网络特别适合处理具有网格结构的数据,如图像。它们使用卷积层来提取图像的特征。 4. **循环神经网络(Recurrent Neural Networks, RNNs)**:这种网络能够处理序列数据,如时间序列或自然语言,因为它们具有记忆功能,能够捕捉数据中的时间依赖性。 5. **长短期记忆网络(Long Short-Term Memory, LSTM)**:LSTM 是一种特殊的 RNN,它能够学习长期依赖关系,非常适合复杂的序列预测任务。 6. **生成对抗网络(Generative Adversarial Networks, GANs)**:由两个网络组成,一个生成器和一个判别器,它们相互竞争,生成器生成数据,判别器评估数据的真实性。 7. **深度学习框架**:如 TensorFlow、Keras、PyTorch 等,这些框架提供了构建、训练和部署深度学习模型的工具和库。 8. **激活函数(Activation Functions)**:如 ReLU、Sigmoid、Tanh 等,它们在神经网络中用于添加非线性,使得网络能够学习复杂的函数。 9. **损失函数(Loss Functions)**:用于评估模型的预测与真实值之间的差异,常见的损失函数包括均方误差(MSE)、交叉熵(Cross-Entropy)等。 10. **优化算法(Optimization Algorithms)**:如梯度下降(Gradient Descent)、随机梯度下降(SGD)、Adam 等,用于更新网络权重,以最小化损失函数。 11. **正则化(Regularization)**:技术如 Dropout、L1/L2 正则化等,用于防止模型过拟合。 12. **迁移学习(Transfer Learning)**:利用在一个任务上训练好的模型来提高另一个相关任务的性能。 深度学习在许多领域都取得了显著的成就,但它也面临着一些挑战,如对大量数据的依赖、模型的解释性差、计算资源消耗大等。研究人员正在不断探索新的方法来解决这些问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值