Java配置的方式
Spring从开始出现到现在,共经历了5个大的版本,并依次推出了3种配置方式:XML配置,注解配置和Java配置。
实现Java配置方式 示例:创建一个userBean:
public class User {
private Integer userId;
private String userName;
public User() {
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
'}';
}
创建一个专门用来配置的配置类 管理User用户类
@Configuration
public class MyConfig {
@Bean
public User user(){
User user = new User();
user.setUserName("小花");
return user;
}
}
在测试类种进行测试:
@SpringBootTest
public class DemopeizhileiApplicationTests {
@Resource(name = "user")
private User user;
@Test
public void contextLoads() {
System.out.println(user);
}
}
打印结果为:可以看到userName赋值成功
整合Mybatis
mybatis-spring方式: 特点: 比较符合SSM整合中的思路.相比第2种方式,操作和配置内容较多. t添加依赖
编写配置文件: 示例:以查询学生为例 创建springboot项目 在pom中添加依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
在springboot配置文件中配置数据源:application.properties文件
#配置数据源
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=175904
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
编写sqlsessionfactory配置类:
@Configuration
public class SqlSessionFactoryConfig {
@Resource
DataSource dataSource;
@Bean
public SqlSessionFactory sqlSessionFactory(){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
try {
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage("com.yay.demomybatis1.pojo");
return sqlSessionFactoryBean.getObject();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
编写MapperScannerConfigurer配置类
@Configuration
public class MapperConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setSqlSessionFactoryBeanName("sqlSessionFactory");
msc.setBasePackage("com.yay.demomybatis1.mapper");
return msc;
}
}
在pojo包下编写Student实体类
public class Student {
private Integer stuId;
private String stuName;
private String stuSex;
private Integer stuAge;
private Integer gradeId;
private Date stuBirth;
@Override
public String toString() {
return "Student{" +
"stuId=" + stuId +
", stuName='" + stuName + '\'' +
", stuSex='" + stuSex + '\'' +
", stuAge=" + stuAge +
", gradeId=" + gradeId +
", stuBirth=" + stuBirth +
'}';
}
在mapper包下编写StudentMapper接口
import java.util.List;
public interface StudentMapper {
public List<Student> listStu();
}
在mapper包下编写StudentMapperSQL映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yay.demomybatis1.mapper.StudentMapper">
<resultMap id="BaseMap" type="student">
<id property="stuId" column="id"/>
<result property="stuName" column="name"/>
<result property="stuSex" column="sex"/>
<result property="stuAge" column="age"/>
<result property="stuBirth" column="birth"/>
<result property="gradeId" column="gradeId"/>
</resultMap>
<select id="listStu" resultMap="BaseMap">
select * from student
</select>
</mapper>
在service包下创建StudentService接口及实现类
public interface StudentService {
public List<Student> list();
}
import javax.annotation.Resource;
import java.util.List;
@Service("studentService")
public class StudentServiceImpl implements StudentService {
@Resource
private StudentMapper stuMapper;
@Override
public List<Student> list() {
return stuMapper.listStu();
}
}
在controller包下创建StudentController控制器类
@Controller
@RequestMapping("/student")
public class StudentController {
@Resource(name = "studentService")
private StudentService studentService;
@RequestMapping("/list")
@ResponseBody
public String list(){
List<Student> list = studentService.list();
return list.toString();
}
}
注意: Maven在打包时,默认只扫描resources中xml及配置文件. 因此我们需要 将映射文件放到此处 或者 指定扫描src/main/java中的配置 在pom文件中加入:因为你的SQL映射文件在mapper包下 默认并不加载resources包之外的配置文件,需要自己指明。
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
启动项目,访问:成功打印 整合Mybatis:mybatis-spring-boot-starter方式 示例 还是以查询student为例
添加依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>
编写application配置文件:
#配置数据源
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=175904
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
#为指定包下的实体类指定别名
mybatis.type-aliases-package=com.yay.mybatisdemo2.pojo
#Mapper映射文件的位置 可以不写 但是必需保证在mapper包下并且名字和Mapper接口名一致
mybatis.mapper-locations=classpath:com/yay/mybatisdemo2/mapper/*.xml
注册SqlSessionFactory: SpringBoot自动完成.
注册Mapper扫描对象: 备注: 此处仅指出了Mapper接口的位置,映射文件必须与Mapper接口在同1位置,且名称为Mapper接口名[方式2]. 方式1: @Mapper标注Mapper接口,在启动入口类中指出扫描Mapper接口所在包 方式2: @MapperScan标注启动入口类或某个Java配置类,声明扫描指定包中的Mapper接口
提供事务管理对象和开启事务管理: SpringBoot自动完成.
在pojo包中编写Student实体类:
public class Student {
private Integer stuId;
private String stuName;
private String stuSex;
private Integer stuAge;
private Integer gradeId;
private Date stuBirth;
@Override
public String toString() {
return "Student{" +
"stuId=" + stuId +
", stuName='" + stuName + '\'' +
", stuSex='" + stuSex + '\'' +
", stuAge=" + stuAge +
", gradeId=" + gradeId +
", stuBirth=" + stuBirth +
'}';
}
编写StudentMapper接口在mapper包中
import java.util.List;
public interface StudentMapper {
public List<Student> listStu();
}
编写StudentMapper.xml映射文件在mapper包中
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yay.mybatisdemo2.mapper.StudentMapper">
<resultMap id="BaseMap" type="student">
<id property="stuId" column="id"/>
<result property="stuName" column="name"/>
<result property="stuSex" column="sex"/>
<result property="stuAge" column="age"/>
<result property="stuBirth" column="birth"/>
<result property="gradeId" column="gradeId"/>
</resultMap>
<select id="listStu" resultMap="BaseMap">
select * from student
</select>
</mapper>
编写StudentService接口及实现类在service包中
public interface StudentService {
public List<Student> list();
}
import javax.annotation.Resource;
import java.util.List;
@Service("studentService")
public class StudentServiceImpl implements StudentService {
@Resource
private StudentMapper stuMapper;
@Override
public List<Student> list() {
return stuMapper.listStu();
}
}
编写StudentController控制器类在controller包中
@Controller
@RequestMapping("/student")
public class StudentController {
@Resource(name = "studentService")
private StudentService studentService;
@RequestMapping("/list")
@ResponseBody
public String list(){
List<Student> list = studentService.list();
return list.toString();
}
}
别忘了在pom中添加:
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
访问成功
整合Redis
步骤:
示例 : 创建springBoot项目 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
编写application配置文件
#配置redis连接参数
#本机可以写为localhost
spring.redis.host=localhost
#Redis服务端连接端口号
spring.redis.port=6379
#spring.redis.password=登录密码 #若未开启密码,则可以省略此配置\
# 默认连接Redis中的指定仓库.
spring.redis.database=0
创建Redis配置类,提供RedisTemplate对象 备注: 1.RedisTemplate对象 用于 存取 数据. 2.RedisTemplate对象默认采用JDK序列化器,对存入的数据进行序列化,对取出的数据进行反序列化操作.[JDK序列化器操作的数据,无法直接显示出原始内容,会乱码]
@Configuration
public class RedisConfig{
@Bean
public RedisTemplate<String ,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<String,Object> ret = new RedisTemplate<String, Object>();
ret.setConnectionFactory(redisConnectionFactory);
return ret;
}
}
第5步: 应用RedisTemplate对象 方式1: 通过Web请求到程序中,在程序中使用RedisTemplate对象调用存取方法进行Redis操作. 方式2: 启动服务时,自动使用RedisTemplate对象调用存取方法进行Redis操作. 方式2:
@Component
public class RWRedis implements CommandLineRunner {
@Resource
private RedisTemplate redisTemplate;
@Override
public void run(String... args) throws Exception {
redisTemplate.opsForValue().set("name","java");
}
}
启动程序 可以看到成功写入了值,因为序列化所以乱码
方式1:新建一个RedisController控制器类 访问改控制器的时候对redis进行操作
@Controller
@RequestMapping("/redis")
public class RedisController {
@Resource
private RedisTemplate redisTemplate;
@RequestMapping("/test")
@ResponseBody
public String testredis(){
String name= (String) redisTemplate.opsForValue().get("name");
在控制台输入name的值
System.out.println(name);
return "你好redis";
}
}
启动项目访问改控制器类: 在控制台中打印了name的值java
|