Spring Boot常见企业开发场景应用、自动配置原理结构分析(二)

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 Tair(兼容Redis),内存型 2GB
简介: Spring Boot常见企业开发场景应用、自动配置原理结构分析

Spring Boot常见企业开发场景应用、自动配置原理结构分析(一)https://developer.aliyun.com/article/1423059


  1. 编写DAO
public interface UserDao {
 User get(int id);
 List findAll();
 void add(User user);
}
@Repository
public class UserDaoImpl extends HibernateDaoSupport implements UserDao{
 // 注入SessionFactory
 @Autowired
 public void autoWiredFactory(SessionFactory sessionFactory) {
  super.setSessionFactory(sessionFactory);
 }
 @Override
 public User get(int id) {
  return getHibernateTemplate().get(User.class, id);
 }
 @Override
 public List findAll() {
  return getHibernateTemplate().findByExample(new User());
 }
 @Override
 public void add(User user) {
  getHibernateTemplate().save(user);
 }
}
  1. 编写Service
public interface UserService {
 /**
  * 根据ID获取用户
  * @param i
  * @return
  */
 User get(int id);
 /**
  * 查询所有用户
  * @return
  */
 List findAll();
 /**
  * 新增用户
  * @param user
  */
 void add(User user);
}
@Service
@Transactional
public class UserServiceImpl implements UserService{
 @Autowired
 private UserDao userDao;
 @Override
 public User get(int id) {
  return userDao.get(id);
 }
 @Override
 public List findAll() {
  return userDao.findAll();
 }
 @Override
 public void add(User user) {
  userDao.add(user);
 }
}
  1. 编写Controller/Handler
@Controller
@RequestMapping("/user")
public class UserController {
 @Autowired
 private UserService userService;
 @RequestMapping("/findUserList")
 public String findUserList(Model model) {
  List list = userService.findAll();
  model.addAttribute("list", list);
  return "/index.jsp";
 }
}
  1. JSP页面参见Servlet/JSP案例
  2. 编写Spring Boot入口
@SpringBootApplication
public class Application {
 public static void main(String[] args) {
  SpringApplication.run(Application.class);
 }
 @Bean
 @ConfigurationProperties(prefix="c3p0")
 public ComboPooledDataSource c3p0DataSource() throws PropertyVetoException {
  return new ComboPooledDataSource();
 }
 @Bean
 @ConfigurationProperties(prefix="hibernate")
 public LocalSessionFactoryBean sessionFactory() throws PropertyVetoException {
  LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
  sessionFactoryBean.setDataSource(c3p0DataSource());
  return sessionFactoryBean;
 }
 @Bean
 public HibernateTransactionManager transactionManager() throws PropertyVetoException {
  HibernateTransactionManager tx = new HibernateTransactionManager();
  tx.setSessionFactory(sessionFactory().getObject());
  return tx;
 }
}
  1. 注意:此处因为Hibernate没有Starter起步依赖,所以我使用了Java配置来整合Hibernate。第一个Bean是C3P0数据源,第二个Bean是SessionFactory,第三个Bean是事务管理器。
  2. 编写配置文件
server.port=10086
server.context-path=/
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql:///springboot
c3p0.user=root
c3p0.password=000000
hibernate.packagesToScan=com.itheima.springboot.entity

构建SSM应用(Spring、Spring MVC、MyBatis)

为了简单起见,这里使用逆向工程生成实体类、Mapper接口、Mapper映射文件。因为查询实体、映射文件的代码比较长,这里就不把代码贴上来了,大家自己使用逆向工程生成下就OK。

  1. 导入依赖

 

org.springframework.boot
    spring-boot-starter-parent
    1.5.14.RELEASE
        org.springframework.boot
        spring-boot-starter-web
        org.springframework.boot
        spring-boot-starter-jdbc
        org.mybatis.spring.boot
        mybatis-spring-boot-starter
        1.3.1
        org.apache.tomcat.embed
        tomcat-embed-jasper
        provided
        mysql
        mysql-connector-java
        5.1.6
        javax.servlet
        jstl
  1. Service代码
public interface UserService {
 /**
  * 根据ID获取用户
  * @param i
  * @return
  */
 TUser get(int id);
 /**
  * 查询所有用户
  * @return
  */
 List findAll();
 /**
  * 新增用户
  * @param user
  */
 void add(TUser user);
}
@Service
@Transactional
public class UserServiceImpl implements UserService{
 @Autowired
 private TUserMapper userMapper;
 @Override
 public TUser get(int id) {
  return userMapper.selectByPrimaryKey(id);
 }
 @Override
 public List findAll() {
  return userMapper.selectByExample(null);
 }
 @Override
 public void add(TUser user) {
  userMapper.insert(user);
 }
}
  1. Controller代码
@Controller
@RequestMapping("/user")
public class UserController {
 @Autowired
 private UserService userService;
 @RequestMapping("/findUserList")
 public String findUserList(Model model) {
  List list = userService.findAll();
  model.addAttribute("list", list);
  return "/index.jsp";
 }
}
  1. Spring Boot入口应用
@SpringBootApplication
@MapperScan(basePackages="com.itheima.springboot.mapper")
public class Application {
 public static void main(String[] args) {
  SpringApplication.run(Application.class);
 }
}
  1. 注意:Spring Boot整合MyBatis需要在Application类上添加@MapperScan,否则不会为Mapper创建代理对象,执行程序失败。
  2. 配置文件
server.port=10086
server.context-path=/
#数据库配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql:///springboot
spring.datasource.username=root
spring.datasource.password=000000
  1. 这里使用默认的数据源,如果想要使用其他的数据源参照之前的配置即可
  2. 访问http://localhost:10086/user/findUserList

构建SSJPA应用(Spring、Spring MVC、Spring Data JPA)

  1. 导入Maven依赖

 

org.springframework.boot
    spring-boot-starter-parent
    1.5.14.RELEASE
        org.springframework.boot
        spring-boot-starter-web
        org.springframework.boot
        spring-boot-starter-data-jpa
        mysql
        mysql-connector-java
        5.1.6
        javax.servlet
        jstl
        org.apache.tomcat.embed
        tomcat-embed-jasper
        c3p0
        c3p0
        0.9.1

 

  1. 注意:导入了spring-boot-starter-data-jpa依赖
  2. 编写Java实体类,参考SSH整合JPA实体类
  3. 编写DAO
public interface UserRepository extends JpaRepository{
}
  1. (这个代码是真的喜欢)
  2. 编写Service
public interface UserService {
 /**
  * 根据ID获取用户
  * @param i
  * @return
  */
 User get(int id);
 /**
  * 查询所有用户
  * @return
  */
 List findAll();
 /**
  * 新增用户
  * @param user
  */
 void add(User user);
}
1. 编写Controller
@Controller
@RequestMapping("/user")
public class UserController {
 @Autowired
 private UserService userService;
 @RequestMapping("/findUserList")
 public String findUserList(Model model) {
  List list = userService.findAll();
  model.addAttribute("list", list);
  return "/index.jsp";
 }
}
1. 编写入口
@SpringBootApplication
public class Application {
 public static void main(String[] args) {
  SpringApplication.run(Application.class);
 }
 @Bean(name="datasource")
 @Primary
 @ConfigurationProperties(prefix="c3p0")
 public ComboPooledDataSource c3p0DataSource() throws PropertyVetoException {
  return new ComboPooledDataSource();
 }
}
1. 配置文件
server.port=10086
server.context-path=/
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql:///springboot
c3p0.user=root
c3p0.password=000000
构建FreeMarker应用程序
1. 导入依赖
  org.springframework.boot
  spring-boot-starter-parent
  1.5.14.RELEASE
   org.springframework.boot
   spring-boot-starter-web
   org.springframework.boot
   spring-boot-starter-data-jpa
   mysql
   mysql-connector-java
   5.1.6
   javax.servlet
   jstl
   org.apache.tomcat.embed
   tomcat-embed-jasper
   c3p0
   c3p0
   0.9.1
   org.springframework.boot
   spring-boot-starter-freemarker
  1. 多导入了spring-boot-starter-freemarker起步依赖
  2. 编写DAO
public interface UserRepository extends JpaRepository{
}
1. 编写Service
public interface UserService {
 /**
  * 根据ID获取用户
  * @param i
  * @return
  */
 User get(int id);
 /**
  * 查询所有用户
  * @return
  */
 List findAll();
 /**
  * 新增用户
  * @param user
  */
 void add(User user);
}
@Service
@Transactional
public class UserServiceImpl implements UserService{
 @Autowired
 private UserRepository userRepository;
 @Override
 public User get(int id) {
  return userRepository.findOne(id);
 }
 @Override
 public List findAll() {
  return userRepository.findAll();
 }
 @Override
 public void add(User user) {
  userRepository.save(user);
 }
}
1. 编写Controller
@Controller
@RequestMapping("/user")
public class UserController {
 // 静态页面输出到的目录
 @Value("${freemarker.output_path}")
 private String OUTPUT_PATH;
 @Autowired
 private UserService userService;
    // 获取FreeMarker配置类
 @Autowired
 private Configuration configuration;
 @RequestMapping("/genPage")
 @ResponseBody
 public Map genPage() throws Exception {
  List list = userService.findAll();
  Map model = new HashMap();
  model.put("list", list);
  Template template = configuration.getTemplate("user_list.ftl");
  template.process(model, new FileWriter(OUTPUT_PATH + "userList.html"));
  Map result = new HashMap();
  result.put("success", true);
  result.put("message", "生成页面成功!");
  return result;
 }
}
1. 编写入口
@SpringBootApplication
public class Application {
 public static void main(String[] args) {
  SpringApplication.run(Application.class);
 }
 @Bean(name="datasource")
 @Primary
 @ConfigurationProperties(prefix="c3p0")
 public ComboPooledDataSource c3p0DataSource() throws PropertyVetoException {
  return new ComboPooledDataSource();
 }
}
1. 编写配置文件
server.port=10086
server.context-path=/
# FreeMarker静态页面输出目录
freemarker.output_path=G:/workspace/free_test/t49/src/main/webapp/
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql:///springboot
c3p0.user=root
c3p0.password=000000
1. 编写FreeMarker模板,此模板默认放在classpath下的template/user_list.ftl中
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
JSP测试
  <#list list as user>
ID
用户名
密码
${user.id}
${user.username}
${user.password}
1. 访问http://localhost:10086/user/genPage,然后检查HTML页面是否生成
构建基于Redis缓存应用程序
1. 导入依赖
 org.springframework.boot
 spring-boot-starter-parent
 1.5.14.RELEASE
 1.8
 org.springframework.boot
 spring-boot-starter-web
 org.springframework.boot
 spring-boot-starter-data-jpa
 mysql
 mysql-connector-java
 5.1.6
 javax.servlet
 jstl
 org.apache.tomcat.embed
 tomcat-embed-jasper
 c3p0
 c3p0
 0.9.1
 org.springframework.boot
 spring-boot-starter-data-redis
1. 要开发导入Redis起步依赖spring-boot-starter-data-redis
2. 编写DAO
 public interface UserRepository extends JpaRepository{
 }
1. 编写Service
public interface UserService {
 /**
  * 根据ID获取用户
  * @param i
  * @return
  */
 User get(int id);
 /**
  * 查询所有用户
  * @return
  */
 List findAll();
 /**
  * 新增用户
  * @param user
  */
 void add(User user);
}
@Service
@Transactional
public class UserServiceImpl implements UserService{
 @Autowired
 private UserRepository userRepository;
 @Autowired
 private RedisTemplate redisTemplate;
 @Override
 public User get(int id) {
  return userRepository.findOne(id);
 }
 @Override
 public List findAll() {
  Long size = redisTemplate.boundListOps("userList").size();
  List userList = redisTemplate.boundListOps("userList").range(0, size);
  if(userList == null || size == 0) {
   System.out.println("从数据库中获取数据...");
   userList = userRepository.findAll();
   System.out.println("将数据放入缓存...");
   redisTemplate.boundListOps("userList").rightPushAll(userList.toArray(new User[0]));
   return userList;
  }
  else {
   System.out.println("从缓存中获取数据...");
   return userList;
  }
 }
 @Override
 public void add(User user) {
  userRepository.save(user);
 }
}
1. 编写Controller
@Controller
@RequestMapping("/user")
public class UserController {
 @Value("${freemarker.output_path}")
 private String OUTPUT_PATH;
 @Autowired
 private UserService userService;
 @RequestMapping("/findUserList")
 public String findUserList(Model model) {
  List list = userService.findAll();
  model.addAttribute("list", list);
  return "/index.jsp";
 }
}
1. 编写Spring Boot入口
@SpringBootApplication
public class Application {
 public static void main(String[] args) {
  SpringApplication.run(Application.class);
 }
 @Bean(name="datasource")
 @Primary
 @ConfigurationProperties(prefix="c3p0")
 public ComboPooledDataSource c3p0DataSource() throws PropertyVetoException {
  ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
  return comboPooledDataSource;
 }
}
1. 编写配置文件
server.port=10086
server.context-path=/
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql:///springboot
c3p0.user=root
c3p0.password=000000
1. 启动Redis
2. 访问http://localhost:10086/user/findUserList,注意控制台的变化
构建基于ActiveMQ消息队列应用程序
1. 导入依赖
 org.springframework.boot
 spring-boot-starter-parent
 1.5.14.RELEASE
 org.springframework.boot
 spring-boot-starter-web
 org.springframework.boot
 spring-boot-starter-data-jpa
 mysql
 mysql-connector-java
 5.1.6
 javax.servlet
 jstl
 org.apache.tomcat.embed
 tomcat-embed-jasper
 c3p0
 c3p0
 0.9.1
 org.springframework.boot
 spring-boot-starter-freemarker
 org.springframework.boot
 spring-boot-starter-activemq
 com.alibaba
 fastjson
 1.2.28


Spring Boot常见企业开发场景应用、自动配置原理结构分析(三)https://developer.aliyun.com/article/1423061

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
相关文章
|
1月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
305 3
|
24天前
|
Java 关系型数据库 数据库
深度剖析【Spring】事务:万字详解,彻底掌握传播机制与事务原理
在Java开发中,Spring框架通过事务管理机制,帮我们轻松实现了这种“承诺”。它不仅封装了底层复杂的事务控制逻辑(比如手动开启、提交、回滚事务),还提供了灵活的配置方式,让开发者能专注于业务逻辑,而不用纠结于事务细节。
|
29天前
|
人工智能 监控 安全
如何快速上手【Spring AOP】?核心应用实战(上篇)
哈喽大家好吖~欢迎来到Spring AOP系列教程的上篇 - 应用篇。在本篇,我们将专注于Spring AOP的实际应用,通过具体的代码示例和场景分析,帮助大家掌握AOP的使用方法和技巧。而在后续的下篇中,我们将深入探讨Spring AOP的实现原理和底层机制。 AOP(Aspect-Oriented Programming,面向切面编程)是Spring框架中的核心特性之一,它能够帮助我们解决横切关注点(如日志记录、性能统计、安全控制、事务管理等)的问题,提高代码的模块化程度和复用性。
|
1月前
|
安全 算法 Java
在Spring Boot中应用Jasypt以加密配置信息。
通过以上步骤,可以在Spring Boot应用中有效地利用Jasypt对配置信息进行加密,这样即使配置文件被泄露,其中的敏感信息也不会直接暴露给攻击者。这是一种在不牺牲操作复杂度的情况下提升应用安全性的简便方法。
576 10
|
2月前
|
安全 Java Nacos
0代码改动实现Spring应用数据库帐密自动轮转
Nacos作为国内被广泛使用的配置中心,已经成为应用侧的基础设施产品,近年来安全问题被更多关注,这是中国国内软件行业逐渐迈向成熟的标志,也是必经之路,Nacos提供配置加密存储-运行时轮转的核心安全能力,将在应用安全领域承担更多职责。
|
2月前
|
NoSQL Java Redis
Redis基本数据类型及Spring Data Redis应用
Redis 是开源高性能键值对数据库,支持 String、Hash、List、Set、Sorted Set 等数据结构,适用于缓存、消息队列、排行榜等场景。具备高性能、原子操作及丰富功能,是分布式系统核心组件。
334 2
|
2月前
|
Java Linux 网络安全
Linux云端服务器上部署Spring Boot应用的教程。
此流程涉及Linux命令行操作、系统服务管理及网络安全知识,需要管理员权限以进行配置和服务管理。务必在一个测试环境中验证所有步骤,确保一切配置正确无误后,再将应用部署到生产环境中。也可以使用如Ansible、Chef等配置管理工具来自动化部署过程,提升效率和可靠性。
284 13
|
2月前
|
缓存 安全 Java
Spring 框架核心原理与实践解析
本文详解 Spring 框架核心知识,包括 IOC(容器管理对象)与 DI(容器注入依赖),以及通过注解(如 @Service、@Autowired)声明 Bean 和注入依赖的方式。阐述了 Bean 的线程安全(默认单例可能有安全问题,需业务避免共享状态或设为 prototype)、作用域(@Scope 注解,常用 singleton、prototype 等)及完整生命周期(实例化、依赖注入、初始化、销毁等步骤)。 解析了循环依赖的解决机制(三级缓存)、AOP 的概念(公共逻辑抽为切面)、底层动态代理(JDK 与 Cglib 的区别)及项目应用(如日志记录)。介绍了事务的实现(基于 AOP
104 0
|
2月前
|
监控 架构师 NoSQL
spring 状态机 的使用 + 原理 + 源码学习 (图解+秒懂+史上最全)
spring 状态机 的使用 + 原理 + 源码学习 (图解+秒懂+史上最全)
|
Java Maven 容器
SpringBoot 核心原理分析
SpringBoot 核心原理分析
251 0
SpringBoot 核心原理分析