springboot的最少maven依赖
<!-- Spring Boot 启动父依赖 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> </parent> <dependencies> <!-- Web 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
托管到spring的bean的获取
一直想优雅地再JavaEE程序中方便地使用集成在spring上的工具,以前的方法是用如下的方式硬编码。
private static ApplicationContext applicationContext;
static {
String path2 = AppUtils.class.getResource("/applicationContext.xml").toString();
String path1 = AppUtils.class.getResource("/applicationContext-myBatis.xml").toString();
applicationContext = new ClassPathXmlApplicationContext(path1,path2);
}
public static <T> T beanFactory(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
如今发现可以用Springboot项目启动自动触发方法,可以很方便地使用spring工具。
@Component
public class InitProject implements ApplicationRunner {
private static final Logger LOG = LoggerFactory.getLogger(InitProject.class);
@Override
public void run(ApplicationArguments args) throws Exception {
LOG.info("==========redis data start===========");
}
}
示例:Springboot整合FastDFS
FastDFS与Springboot集成_技术改变生活-CSDN博客_fastdfs springboot
1.添加pom依赖
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.25.2-RELEASE</version>
</dependency>
2、将Fdfs配置引入项目
@Import(FdfsClientConfig.class)
@SpringBootApplication
public class JingtongApplication {
public static void main(String[] args) {
SpringApplication.run(JingtongApplication.class, args);
}
}
3.配置文件中加入fdfs相关配置
application.yml
fdfs:
soTimeout: 1500
connectTimeout: 600
thumbImage: #缩略图生成参数
width: 150
height: 150
trackerList: #TrackerList参数,支持多个
- 192.168.0.201:22122
- 192.168.0.202:22122
application.properties
fdfs.soTimeout=1500
fdfs.connectTimeout=600
fdfs.thumbImage.width=150
fdfs.thumbImage.height=150
fdfs.trackerList[0]=192.168.0.201:22122
fdfs.trackerList[1]=192.168.0.202:22122
4.简单封装FastDFS使用类
package com.example.components;
import com.github.tobato.fastdfs.FdfsClientConfig;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
//解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@Import(FdfsClientConfig.class)//只需要一行注解 @Import(FdfsClientConfig.class)就可以拥有带有连接池的FastDFS Java客户端了
@Component
public class FastDFSClientWrapper {
@Autowired
private FastFileStorageClient storageClient;
public String uploadFile(File source) throws IOException {
FileInputStream is=null;
try {
is = new FileInputStream(source);
StorePath storePath = storageClient.uploadFile(is, source.length(), FilenameUtils.getExtension(source.getName()), null);
return getResAccessUrl(storePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(is!=null){
is.close();
}
}
return null;
}
// 封装文件完整URL地址
private String getResAccessUrl(StorePath storePath) {
String fileUrl = "192.168.10.183:80" + "/" + storePath.getFullPath();
return fileUrl;
}
}
5.项目启动自动触发方法
package com.example.components;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.io.File;
@Component
public class InitProject implements ApplicationRunner {
@Autowired
private FastDFSClientWrapper fastDFSClientWrapper;
@Override
public void run(ApplicationArguments args) throws Exception {
//在这里写数据逻辑
System.out.println("start upload job!!!!!!!!!");
String pathname = "C:\\Users\\76204\\Postman\\files\\youyin_test1.mp4";
pathname = "D:\\test\\test.png";
String path = fastDFSClientWrapper.uploadFile(new File(pathname));
System.out.println("path========>>>>>"+path);
}
}
6.项目入口
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
//在启动类下添加扫描路径
@ComponentScan(basePackages = {"com.example.components"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
7.测试类
package com.example.demo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.*;
@SpringBootTest
class SpringbootApplicationTest
{
@Autowired
private FastFileStorageClient storageClient;
/**
* 文件上传
*/
@Test
public void uploadTest()
{
InputStream is = null;
try
{
// 获取文件源
// File source = new File("C:\\Users\\76204\\Postman\\files\\youyin_test1.mp4");
File source = new File("D:\\test\\test.png");
// 获取文件流
is = new FileInputStream(source);
// 进行文件上传
StorePath storePath = storageClient.uploadFile(is, source.length(), FilenameUtils.getExtension(source.getName()), null);
// 获得文件上传后访问地址
String fullPath = storePath.getFullPath();
// 打印访问地址
System.out.println("fullPath = " + fullPath);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
try
{
if(is != null)
{
// 关闭流资源
is.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
扩充:
使用过程中发现了一个很好用的注解@PostConstruct注解
这个注解是由Java提供的,它用来修饰一个非静态的void方法。它会在服务器加载Servlet的时候运行,并且只运行一次。
@Component
public class SystemConstant {
public static String surroundings;
@Value("${spring.profiles.active}")
public String environment;
@PostConstruct
public void initialize() {
System.out.println("初始化环境...");
surroundings = this.environment;
}
}
这个注解还可以方便地将自动装配地类供static工具类使用,例如
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* @ClassName RedisUtil
*/
@Component
public class RedisUtil {
private static RedisTemplate<Object, Object> redisTemplates;
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
@PostConstruct
public void initialize() {
redisTemplates = this.redisTemplate;
}
/**
* 添加元素
*
* @param key
* @param value
*/
public static void set(Object key, Object value) {
if (key == null || value == null) {
return;
}
redisTemplates.opsForValue().set(key, value);
}
}
关闭banner和web模式
application.yaml
spring:
main:
web-application-type: none
banner-mode: off
非 Spring 管理环境获取 Bean
个人感觉基于SpringBoot启动实现和通过通过BeanFactoryPostProcessor最为方便,而且相对于基于SpringBoot启动实现多了一步注入ac的操作,我更喜欢通过BeanFactoryPostProcessor。
基于SpringBoot启动实现
@SpringBootApplication
public class ExampleApplication {
public static void main(String[] args) {
// 启动时,保存上下文,并保存为静态
ConfigurableApplicationContext ac = SpringApplication.run(ExampleApplication.class, args);
SpringContextUtil.setAc(ac);
}
}
public class SpringContextUtil1 {
private static ApplicationContext ac;
public static <T> T getBean(String beanName, Class<T> clazz) {
T bean = ac.getBean(beanName, clazz);
return bean;
}
public static void setAc(ApplicationContext applicationContext){
ac = applicationContext;
}
}
通过BeanFactoryPostProcessor
package com.example.user.util;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
@Component
public final class SpringUtils implements BeanFactoryPostProcessor {
/** Spring应用上下文环境 */
private static ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
SpringUtils.beanFactory = beanFactory;
}
/**
* 获取对象
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws org.springframework.beans.BeansException
*
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException
{
return (T) beanFactory.getBean(name);
}
/**
* 获取类型为requiredType的对象
*
* @param clz
* @return
* @throws org.springframework.beans.BeansException
*
*/
public static <T> T getBean(Class<T> clz) throws BeansException
{
T result = (T) beanFactory.getBean(clz);
return result;
}
/**
* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
*
* @param name
* @return boolean
*/
public static boolean containsBean(String name)
{
return beanFactory.containsBean(name);
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
*
* @param name
* @return boolean
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.isSingleton(name);
}
/**
* @param name
* @return Class 注册对象的类型
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getType(name);
}
/**
* 如果给定的bean名字在bean定义中有别名,则返回这些别名
*
* @param name
* @return
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getAliases(name);
}
}
ConfigurableApplicationContext ac = SpringApplication.run(DemoApplication.class, args);
以后可以理解为springboot完成了配置的加载工作,加载完成以后SpringContextUtil就可以方便使用了。
package com.example;
import com.example.user.entity.User;
import com.example.user.mapper.UserMapper;
import com.example.user.util.SpringContextUtil;
import com.example.user.util.SpringUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.List;
@SpringBootApplication
@MapperScan("com.example.user.mapper") //填写对应mapper存放位置,自动识别mapper下的所有**Mapper
public class DemoApplication {
public static void main(String[] args) {
//可以理解为在这一步完成了所有配置的加载
ConfigurableApplicationContext ac = SpringApplication.run(DemoApplication.class, args);
// UserMapper userMapper = SpringContextUtil.getBean(UserMapper.class);
UserMapper userMapper = SpringUtils.getBean(UserMapper.class);
List<User> users = userMapper.selectList(null);
for (User user : users) {
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>"+user);
}
//关闭
ac.close();
}
}
来源:
Spring获取Bean的9种方式-腾讯云开发者社区-腾讯云
springboot整合mybatis-plus以及代码生成器
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.14</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
</properties>
<dependencies>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!-- log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--junit测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mybatis-plus 代码生成-->
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.4.3.4</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.0</version>
</dependency>
<!--代码生成模式插件 3.0.3以后需要手动设置依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<!--代码生成模板-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<!--swagger2-->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>spring-boot-starter-swagger</artifactId>
<version>1.5.1.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
# mysql连接信息
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/testMyBatisPlus?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
username: root
password: 123456
thymeleaf:
cache: false #设置为false,否则会有缓存,导致页面没法及时看到更新后的效果。
#仅仅处理数据,不启用web
main:
web-application-type: none
banner-mode: off
#mybatis-plus相关配置
mybatis-plus:
mapper-locations: classpath:mapper/*.xml #扫描mapper下的所有xml文件
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
type-aliases-package: com.example.user.entity #扫描实体类包/配置别名
代码生成器使用
package com.example.client;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
import java.util.List;
/**
* @author by 测试
* @date 2022/12/22
*/
public class CodeGenerator {
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
//当前路径
String projectPath = System.getProperty("user.dir");
//输出路径
gc.setOutputDir(projectPath + "/src/main/java");
//设置作者
gc.setAuthor("测试");
//生成代码后,是否打开文件夹
gc.setOpen(true);
//是否覆盖原来代码,个人建议设置为false,别覆盖,危险系数太高
gc.setFileOverride(true);
//去掉service的I前缀,一般只需要设置service就行
gc.setServiceName("I%sService");
gc.setEntityName("%s");
//日期格式
gc.setDateType(DateType.ONLY_DATE);
//日期格式
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
//指定数据库的类型
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
//自定义包的路径
pc.setParent("com.example");
//模块名称 设置后,会生成com.cxyxs.test.module,里面存放之前设置的mapper,entity
pc.setModuleName("user");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//设置映射的表名,可以设置多个表
strategy.setInclude("t_user");
//表前缀设置 d_student
strategy.setTablePrefix(new String[]{"t_"});
//包的命名规则,使用驼峰规则
strategy.setNaming(NamingStrategy.underline_to_camel);
//列的名称,使用驼峰规则
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//是否使用lombok
strategy.setEntityLombokModel(true);
//驼峰命名
strategy.setRestControllerStyle(true);
//逻辑删除,假删除会用到
strategy.setLogicDeleteFieldName("is_delete");
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
//自动填充字段,在项目开发过程中,例如创建时间,修改时间,每次,都需要我们来指定,太麻烦了,设置为自动填充规则,就不需要我们赋值咯
TableFill fillInsert = new TableFill("create_time", FieldFill.INSERT);
TableFill fillUpdate= new TableFill("update_time", FieldFill.UPDATE);
List fillLists = new ArrayList();
fillLists.add(fillInsert);
fillLists.add(fillUpdate);
strategy.setTableFillList(fillLists);
//乐观锁
//strategy.setVersionFieldName("version");
mpg.setStrategy(strategy);
//执行
mpg.execute();
}
}
测试数据
DROP DATABASE IF EXISTS testMyBatisPlus;
CREATE DATABASE testMyBatisPlus;
USE testMyBatisPlus;
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
use testMyBatisPlus;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@qq.com'),
(2, 'Jack', 20, 'test2@qq.com'),
(3, 'Tom', 28, 'test3@qq.com'),
(4, 'Sandy', 21, 'test4@qq.com'),
(5, 'Billie', 24, 'test5@qq.com');
来源:
mybatis-plus 代码生成_mybatisplus 代码生成_倪惊鸿的博客-CSDN博客
Springboot+Mybatis-puls整合_spring引入mybatisplus_遗 憾♡ۣۖ的博客-CSDN博客