纯注解开发配置spring

1.纯注解开发【定义配置类的注解】

==@Confituration == 表示该类是一个配置类
==@ComponentScan(“com.itheima”) == 配置包扫描
@PropertySource(“classpath:jdbc.properties”) 加载属性文件
==@Import(JdbcConfig.class) == 加载其他配置类

2.spring整合mybatis【纯注解,3个配置类】

<1>SpringConfig配置类

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;@Configuration //表示该类是一个配置类,用来代替applicationContext.xml,这个注解可以不写,但是一般都写了
//<context:component-scan base-package="com.itheima"/>
@ComponentScan("com.itheima") //Spring包扫描
//<context:property-placeholder location="classpath*:*.properties"/>
@PropertySource("classpath:jdbc.properties") //加载属性文件
// <import resource="classpath:applicationContext-dao.xml"/>
@Import(JdbcConfig.class)  //引入分配置类
public class SpringConfig {
}

<2>JdbcConfig配置类

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class JdbcConfig {@Value("${jdbc.driver}")private String driverClassName;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Beanpublic DataSource dataSource() {DruidDataSource ds = new DruidDataSource();ds.setDriverClassName(driverClassName);ds.setUrl(url);ds.setUsername(username);ds.setPassword(password);return ds;}
}

<3>MybatisConfig 配置

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;public class MybatisConfig {@Beanpublic SqlSessionFactoryBean SqlSessionFactoryBean(@Autowired DataSource dataSource){SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();//1.注入连接池对象【必须】ssfb.setDataSource(dataSource);//2.加载MybatisConfig.xml核心配置文件,// 如果核心配置文件中的内容都被抽取了,那么就可以不用加载【可选】//ClassPathResource resource = new ClassPathResource("classpath:MybatisConfig.xml");//ssfb.setConfigLocation(resource);//3 配置别名,如果是使用注解配置SQL语句,可以不用配置别名【可选】//ssfb.setTypeAliasesPackage("com.itheima.bean");//4 加载映射配置文件,如果映射配置文件和mapper接口在同一个包下,并且同名,那么会自动加载【可选】//ClassPathResource resource = new ClassPathResource("classpath:StudentMapper.xml");//ssfb.setMapperLocations(resource);return ssfb;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer msc = new MapperScannerConfigurer();msc.setBasePackage("com.itheima.mapper");return msc;}
}

3.具体实现类及测试类

<1>StudentServiceImpl类:

package com.itheima.service.impl;import com.itheima.bean.Student;
import com.itheima.mapper.StudentMapper;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.io.IOException;
import java.util.List;@Service("studentService")
public class StudentServiceImpl implements StudentService {@Autowiredprivate StudentMapper mapper;//注入StudentMapper的代理对象@Overridepublic List<Student> selectAll() throws IOException {return mapper.selectAll();}@Overridepublic Student selectById(Integer id) throws IOException {return mapper.selectById(id);}@Overridepublic Integer insert(Student stu) throws IOException {return mapper.insert(stu);}@Overridepublic Integer update(Student stu) throws IOException {return mapper.update(stu);}@Overridepublic Integer delete(Integer id) throws IOException {return mapper.delete(id);}
}

<2>studentMapper类

package com.itheima.mapper;
import com.itheima.bean.Student;
import org.apache.ibatis.annotations.*;import java.util.List;
public interface StudentMapper {//查询全部@Select("select * from student")public abstract List<Student> selectAll();//根据id查询@Select("select * from student where id=#{ID}")public abstract Student selectById(Integer id);//新增数据@Insert("insert into student values(null,#{name},#{age})")public abstract Integer insert(Student stu);//修改数据@Update("update student set name=#{name},age=#{age} where id=#{id}")public abstract Integer update(Student stu);//删除数据@Delete(" delete from student where id=#{id}")public abstract Integer delete(Integer id);
}

<3>jdbc.properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
#不加Jdbc系统会默认username为系统用户名
jdbc.username=root
jdbc.password=123456

❤️-4>测试类:

获取容器方式为加载配置类:

    @Testpublic void test1() throws IOException {//从美IOC中取studentService对象//ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);StudentService studentService = applicationContext.getBean("studentService", StudentService.class);List<Student> list = studentService.selectAll();list.forEach(stu-> System.out.println(stu));}打印结果:
---------------------------------------------------------------------
Student{id=1, name='张三', age=23}
Student{id=2, name='李四', age=24}
Student{id=15, name='小郭', age=22}

4.spring整合junit单元测试

前提:添加spring-test和junit依赖,并且junit依赖的版本必须大于等于4.12版本。

【第一步】

 <!--junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><!--Spring整合junit单元测试--><!--junit的依赖至少要是4.12版本,可以是4.13等版本,否则出现如下异常--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.1.9.RELEASE</version></dependency>

【第二步】
spring的Junit测试类整合

import com.itheima.bean.Student;
import com.itheima.config.SpringConfig;
import com.itheima.service.StudentService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.io.IOException;
import java.util.List;//【第二步】使用spring中提供的单元测试运行类替换JVM中单元测试运行类
@RunWith(SpringJUnit4ClassRunner.class)
//【第三步】加载配置文件或者配置类[将bean对象注入容器]
@ContextConfiguration(classes = {SpringConfig.class})
public class StudentJunit {@Autowired//[将studentService采用set注入方式,则不能new容器对象获取]private StudentService studentService;@Testpublic void test1() throws IOException {List<Student> list = studentService.selectAll();//断言测试,与预期一致则通过,反正爆出不同的地方Assert.assertEquals(24,list.size());}@Testpublic void test2() throws IOException {Student stu = studentService.selectById(20);Assert.assertEquals("陈锦涛",stu.getName());}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/330650.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

阿里巴巴对Java编程【命名风格】的规约

转载自 阿里巴巴对Java编程【命名风格】的规约 命名风格 1. 【强制】代码中的命名均不能以下划线或美元符号开始&#xff0c;也不能以下划线或美元符号结束。 反例&#xff1a; _name / __name / $Object / name_ / name$ / Object$ 2. 【强制】代码中的命名严禁使用拼音与英文…

linux-basic(10)vim程序编辑器

【10.1】vi 与 vim【10.2】vi的使用1&#xff09;3种模式&#xff1a;模式1&#xff1a;一般模式&#xff0c; vim打开就是这种模式&#xff0c;编辑模式下 按 esc 回到一般模式&#xff1b;模式2&#xff1a;编辑模式&#xff0c;要等到你按下『i, I, o, O, a, A, r, R』等任何…

阿里巴巴对Java编程【代码格式】的规约

转载自 阿里巴巴对Java编程【代码格式】的规约 代码格式 1. 【强制】大括号的使用约定。如果是大括号内为空&#xff0c;则简洁地写成{}即可&#xff0c;不需要换行 &#xff1b; 如果是非空代码块则&#xff1a; 1 &#xff09; 左大括号前不换行。 2 &#xff09; 左大括号后…

自定义通配器导入bean对象

1.CustomerImportSelector工具类&#xff1a; /*** description : 自动导入器* author : wanYunBo* date : 2021-09-02 20:46**/ package com.itheima.config.selector;import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import o…

linux-basic(11)认识和学习bash

【11.1】认识bash这个shell1&#xff09;介绍&#xff1a;其实壳程序的功能只是提供用户操作系统的一个接口&#xff0c;因此这个壳程序需要可以呼叫其他软件才好。命令&#xff0c;包括 man, chmod, chown, vi, fdisk, mkfs 等等命令&#xff0c;这些命令都是独立的应用程序&a…

阿里巴巴对Java编程【常量定义】的规约

转载自 阿里巴巴对Java编程【常量定义】的规约 常量定义 1. 【强制】不允许任何魔法值 &#xff08; 即未经定义的常量 &#xff09; 直接出现在代码中。 反例&#xff1a; String key " Id # taobao _" tradeId; cache . put(key , value); 2. 【强制】 long 或…

动态代理-AOP

1 什么是AOP&#xff1f; Aspect Oriented Programming的缩写&#xff0c;面向切面编程&#xff0c;切面指定就是动态代理的方法&#xff0c;作用是在不改变业务层方法源代码的基础上对方法进行增强&#xff0c;底层使用的是动态代理技术&#xff0c;面向切面编程也可以理解成…

linux-basic(12)正则表达式与文件格式化处理

【12.1.1】什么是正则表达式&#xff1f; 1&#xff09;简单说&#xff1a;正则表示法就是处理字串的方法&#xff0c;他是以行为单位来进行字串的处理行为&#xff0c; 正则表达式透过一些特殊符号的辅助&#xff0c;可以让使用者轻易的达到查找、删除、替换某特定字串的处理程…

阿里巴巴对Java编程【OOP规约】的规约

转载自 阿里巴巴对Java编程【OOP规约】的规约 OOP规约 1. 【强制】避免通过一个类的对象引用访问此类的静态变量或静态方法&#xff0c;无谓增加编译器解析成本&#xff0c;直接用类名来访问即可。 2. 【强制】所有的覆写方法&#xff0c;必须加 Override 注解。 说明&#xff…

AOP切点表达式及通知类参数传递方式

1.切入点表达式的写法 execution( * com.itheima.service.impl.StudentServiceImpl.findAll(…)) //较少 execution( * com.itheima.service.impl.StudentServiceImpl.(…)) //较少 execution( * com.itheima.service.StudentService.(…)) //StudentService中的所有方法会被代…

linux-basic(13)学习shell script

【13.1】什么是shell script&#xff1f;1&#xff09;shell script 是利用 shell 的功能所写的一个『程序 (program)』&#xff0c;这个程序是使用纯文字档&#xff0c;将一些 shell 的语法与命令(含外部命令)写在里面&#xff0c; 搭配正规表示法、管线命令与数据流重导向等功…

阿里巴巴对Java编程【集合处理】的规约

转载自 阿里巴巴对Java编程【集合处理】的规约集合处理1. 【强制】关于 hashCode 和 equals 的处理&#xff0c;遵循如下规则&#xff1a; 1&#xff09; 只要重写 equals &#xff0c;就必须重写 hashCode 。 2&#xff09; 因为 Set 存储的是不重复的对象&#xff0c;依据 ha…

http请求状态码400的原因总结

会出现这个HTTP请求状态码400&#xff0c;说明这个请求是无效的&#xff0c;并没有进入后台服务器&#xff08;控制器&#xff09;里。 通常的原因&#xff1a; 前端提交的字段名称或者字段类型和后台的实体类不一样&#xff0c;或者前端提交的参数跟后台需要的参数个数不一致…

做一个完整的Java Web项目需要掌握的技能

转自&#xff1a; https://blog.csdn.net/JasonLiuLJX/article/details/51494048--------------------------------------------------------------------------------最近自己做了几个Java Web项目&#xff0c;有公司的商业项目&#xff0c;也有个人做着玩的小项目&#xff0…

阿里巴巴对Java编程【并发处理】的规约

转载自 阿里巴巴对Java编程【并发处理】的规约并发处理1. 【强制】获取单例对象需要保证线程安全&#xff0c;其中的方法也要保证线程安全。 说明&#xff1a;资源驱动类、工具类、单例工厂类都需要注意。2. 【强制】创建线程或线程池时请指定有意义的线程名称&#xff0c;方便…

查询sql打印日志配置

mybatis-plus:mapper-locations: classpath*:mapper/*.xml# 设置别名包扫描路径&#xff0c;通过该属性可以给包中的类注册别名type-aliases-package: com.heima.model.user.pojosconfiguration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

js语法+dom+js图片库+最佳实践+图片库改进版

【2】js语法 【2.2.4】数据类型类型1&#xff09;字符串 var mood happy; var moood "happy"; 类型2&#xff09;数值&#xff1b; var age 33.24; 类型3&#xff09;布尔值&#xff1b;var married true; 【2.2.5】数组1&#xff09;填充方式 填充方式1&#xf…

RabbitMQ--topic

Topic类型的Exchange与Direct相比&#xff0c;都是可以根据RoutingKey把消息路由到不同的队列。只不过Topic类型Exchange可以让队列在绑定Routing key 的时候使用通配符&#xff01; Routingkey 一般都是有一个或多个单词组成&#xff0c;多个单词之间以”.”分割&#xff0c;…

阿里巴巴对Java编程【控制语句】的规约

转载自 阿里巴巴对Java编程【控制语句】的规约控制语句1. 【强制】在一个 switch 块内&#xff0c;每个 case 要么通过 break / return 等来终止&#xff0c;要么注释说明程序将继续执行到哪一个 case 为止 &#xff1b; 在一个 switch 块内&#xff0c;都必须包含一个 default…

RabbitMQ消息

如何确保RabbitMQ消息的可靠性&#xff1f; 开启生产者确认机制&#xff0c;确保生产者的消息能到达队列开启持久化功能&#xff0c;确保消息未消费前在队列中不会丢失开启消费者确认机制为auto&#xff0c;由spring确认消息处理成功后完成ack开启消费者失败重试机制&#xff…