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

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
简介: 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数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
18天前
|
Cloud Native Java Nacos
springcloud/springboot集成NACOS 做注册和配置中心以及nacos源码分析
通过本文,我们详细介绍了如何在 Spring Cloud 和 Spring Boot 中集成 Nacos 进行服务注册和配置管理,并对 Nacos 的源码进行了初步分析。Nacos 作为一个强大的服务注册和配置管理平台,为微服务架构提供
248 14
|
21天前
|
Java 数据库 开发者
详细介绍SpringBoot启动流程及配置类解析原理
通过对 Spring Boot 启动流程及配置类解析原理的深入分析,我们可以看到 Spring Boot 在启动时的灵活性和可扩展性。理解这些机制不仅有助于开发者更好地使用 Spring Boot 进行应用开发,还能够在面对问题时,迅速定位和解决问题。希望本文能为您在 Spring Boot 开发过程中提供有效的指导和帮助。
71 12
|
2月前
|
Dart 前端开发 JavaScript
springboot自动配置原理
Spring Boot 自动配置原理:通过 `@EnableAutoConfiguration` 开启自动配置,扫描 `META-INF/spring.factories` 下的配置类,省去手动编写配置文件。使用 `@ConditionalXXX` 注解判断配置类是否生效,导入对应的 starter 后自动配置生效。通过 `@EnableConfigurationProperties` 加载配置属性,默认值与配置文件中的值结合使用。总结来说,Spring Boot 通过这些机制简化了开发配置流程,提升了开发效率。
87 17
springboot自动配置原理
|
8天前
|
存储 监控 数据可视化
SaaS云计算技术的智慧工地源码,基于Java+Spring Cloud框架开发
智慧工地源码基于微服务+Java+Spring Cloud +UniApp +MySql架构,利用传感器、监控摄像头、AI、大数据等技术,实现施工现场的实时监测、数据分析与智能决策。平台涵盖人员、车辆、视频监控、施工质量、设备、环境和能耗管理七大维度,提供可视化管理、智能化报警、移动智能办公及分布计算存储等功能,全面提升工地的安全性、效率和质量。
|
2月前
|
JavaScript Java 程序员
SpringBoot自动配置及自定义Starter
Java程序员依赖Spring框架简化开发,但复杂的配置文件增加了负担。SpringBoot以“约定大于配置”理念简化了这一过程,通过引入各种Starter并加载默认配置,几乎做到开箱即用。
139 10
SpringBoot自动配置及自定义Starter
|
2月前
|
监控 Java 应用服务中间件
SpringBoot是如何简化Spring开发的,以及SpringBoot的特性以及源码分析
Spring Boot 通过简化配置、自动配置和嵌入式服务器等特性,大大简化了 Spring 应用的开发过程。它通过提供一系列 `starter` 依赖和开箱即用的默认配置,使开发者能够更专注于业务逻辑而非繁琐的配置。Spring Boot 的自动配置机制和强大的 Actuator 功能进一步提升了开发效率和应用的可维护性。通过对其源码的分析,可以更深入地理解其内部工作机制,从而更好地利用其特性进行开发。
59 6
|
2月前
|
Java 应用服务中间件 API
【潜意识Java】javaee中的SpringBoot在Java 开发中的应用与详细分析
本文介绍了 Spring Boot 的核心概念和使用场景,并通过一个实战项目演示了如何构建一个简单的 RESTful API。
53 5
|
2月前
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
93 2
|
2月前
|
人工智能 Java API
阿里云工程师跟通义灵码结伴编程, 用Spring AI Alibaba来开发 AI 答疑助手
本次分享的主题是阿里云工程师跟通义灵码结伴编程, 用Spring AI Alibaba来开发 AI 答疑助手,由阿里云两位工程师分享。
115 0
阿里云工程师跟通义灵码结伴编程, 用Spring AI Alibaba来开发 AI 答疑助手
|
2月前
|
监控 JavaScript 数据可视化
建筑施工一体化信息管理平台源码,支持微服务架构,采用Java、Spring Cloud、Vue等技术开发。
智慧工地云平台是专为建筑施工领域打造的一体化信息管理平台,利用大数据、云计算、物联网等技术,实现施工区域各系统数据汇总与可视化管理。平台涵盖人员、设备、物料、环境等关键因素的实时监控与数据分析,提供远程指挥、决策支持等功能,提升工作效率,促进产业信息化发展。系统由PC端、APP移动端及项目、监管、数据屏三大平台组成,支持微服务架构,采用Java、Spring Cloud、Vue等技术开发。
115 7