springboot的所学所想(二)

一.springboot集成MybatisPlus

      Mybatisplus的优点:

      1.通用CRUD:集成BaseMapper就可以使用MP封装的CRUD

                      多种主键策略:IdType.AUTO(自动),IdType.INPUT(用户输入),IdType.ID_WORKER(自动),                                            IdType.UUID(自动)。配置方法,主键ID上加上注解:@TableId(value = "ID", type = IdType.AUTO),一                                        般情况下推荐大家使用自动增长主键。

       2.内置分页插件:Page内置分页插件。

       3.代码生成:MP自带代码生成工具,可以从Controller层直接生成到mapper层,包括实体类,让我们只关心请求地址和业务处                              理。

集成Mybaits-Plus

        在pom.xml文件下导入如下依赖

<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.1.4</version>
</dependency>

然后新建一个com.majiaxueyuan.config用来存储配置信息类的包,新建一个配置Mybatis-Plus的类MybatisPlusConfig具体内容如下,同学们不需要记住配置的具体内容是什么,你大概能看懂是什么意思就懂了。在SpringBoot中使用配置文件时,务必在类上加上Configuration的注解方便系统启动时加载。

@Configuration
public class MybatisPlusConfig {
@Autowired
   private DataSource dataSource;
   @Autowired
   private MybatisProperties properties;
   @Autowired
   private ResourceLoader resourceLoader = new DefaultResourceLoader();
   @Autowired(required = false)
   private Interceptor[] interceptors;
   @Autowired(required = false)
   private DatabaseIdProvider databaseIdProvider;
   /**
    *   mybatis-plus分页插件
    */
   @Bean
   public PaginationInterceptor paginationInterceptor() {
       PaginationInterceptor page = new PaginationInterceptor();
       page.setDialectType("mysql");
       return page;
   }
   /**
    * 这里全部使用mybatis-autoconfigure 已经自动加载的资源。不手动指定
    * 配置文件和mybatis-boot的配置文件同步
    * @return
    */
   @Bean
   public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
       MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
       mybatisPlus.setDataSource(dataSource);
       mybatisPlus.setVfs(SpringBootVFS.class);
       if (StringUtils.hasText(this.properties.getConfigLocation())) {
           mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
       }
       mybatisPlus.setConfiguration(properties.getConfiguration());
       if (!ObjectUtils.isEmpty(this.interceptors)) {
           mybatisPlus.setPlugins(this.interceptors);
       }
       MybatisConfiguration mc = new MybatisConfiguration();
       mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
       mybatisPlus.setConfiguration(mc);
       if (this.databaseIdProvider != null) {
           mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
       }
       if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
           mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
       }
       if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
           mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
       }
       if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
           mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
       }
       return mybatisPlus;
   }
}

通用CRUD

到这里,Mybatis-Plus已经全部集成到系统里面去了,然后我们就来改造我们之前的UserMapper,就是删除掉里面的内容然后继承至Mybatis-Plus相关内容就可以了,代码如下:

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

BaseMapper中封装来许多对数据库操作的方法,可以直接拿来用。然后我们改造一下我们的Service层,只需要将里面调用的方法进行一个更改就可以了。

然后我们需要对实体类进行一个简单的修饰,并且告诉MP该表的主键是什么,然后主键的生成策略是什么(举例子)。

@TableName("user")
public class User {

@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String username;

然后我们这里来执行一下条件查询,这里我们要用到Mybatis-Plus中的包装(Wrapper)去构建我们的条件查询下面举几个Wrapper语句的示例,

Wrapper<T> wrapper = new EntityWrapper<>();           构建一个实体类的包装工具
wrapper.eq("username", "LIAOXIANG");                  做条件判断            
wrapper.between("id", 0, 100);                        做范围判断
wrapper.groupBy("username");                          分组
wrapper.isNotNull("username");                        不为空判断
wrapper.orderBy("id", false);                         排序,从小打大为true,反之false

分页查询

public Object selectPage(Integer pagenum,Integer pagesize){
    Wrapper wrapper=new EntityWrapper<>();
    RowBounds rowBounds=new RowBounds((pagenum-1)*pagesize,pagesize);
    return userMapper.selectPage(rowBounds,wrapper);
}

代码生成工具

使用我们的代码生成工具,需要导入一个模版引擎:

在pom.xml文件中导入一下包

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>

配置类(网上拷贝的代码)

public class MysqlGenerator {

  
    public static void main(String[] args) {
        /* 获取 JDBC 配置文件 */
        Properties props = getProperties();
        AutoGenerator mpg = new AutoGenerator();

        String outputDir = "E:/code";
        final String viewOutputDir = outputDir + "/view/";
    
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(outputDir);
        gc.setFileOverride(true);
        gc.setActiveRecord(true);// 开启 activeRecord 模式
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        gc.setAuthor("cdy");
    
        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("I%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.SQL_SERVER);
        dsc.setTypeConvert(new MySqlTypeConvert());
        dsc.setDriverName(props.getProperty("spring.datasource.driver-class-name"));
//          dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(props.getProperty("spring.datasource.username"));
        dsc.setPassword(props.getProperty("spring.datasource.password"));
        dsc.setUrl(props.getProperty("spring.datasource.url"));
        mpg.setDataSource(dsc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        // strategy.setCapitalMode(true);// 全局大写命名
        // strategy.setDbColumnUnderline(true);//全局下划线命名
//      strategy.setTablePrefix(new String[] { "bmd_", "mp_" });// 此处可以修改为您的表前缀
         strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
         strategy.setInclude(new String[] {"station"}); // 需要生成的表
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表
        // 自定义实体父类
        // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
        // 自定义实体,公共字段
        // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
        // 自定义 mapper 父类
        // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
        // 自定义 service 父类
        // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
        // 自定义 service 实现类父类
        // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
        // 自定义 controller 父类
        strategy.setSuperControllerClass("com.dream.team.base.BController");
        // 【实体】是否生成字段常量(默认 false)
        // public static final String ID = "test_id";
        // strategy.setEntityColumnConstant(true);
        // 【实体】是否为构建者模型(默认 false)
        // public User setName(String name) {this.name = name; return this;}
        // strategy.setEntityBuliderModel(true);
        mpg.setStrategy(strategy);

        // 包配
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);  //所属模块
        pc.setParent("com.dream.team"); // 自定义包路径
        pc.setController("controller"); // 这里是控制器包名,默认 web
        pc.setEntity("model");
        pc.setXml("sqlMapperXml");
        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {}
        };
        // 生成的模版路径,不存在时需要先新建
        File viewDir = new File(viewOutputDir);
        if (!viewDir.exists()) {
            viewDir.mkdirs();
        }
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
    /*focList.add(new FileOutConfig("/templates/add.jsp.vm") {
        @Override
        public String outputFile(TableInfo tableInfo) {
            return getGeneratorViewPath(viewOutputDir, tableInfo, "Add.jsp");
        }
    });*/
    /*focList.add(new FileOutConfig("/templates/list.js.vm") {
        @Override
        public String outputFile(TableInfo tableInfo) {
            return getGeneratorViewPath(viewOutputDir, tableInfo, "List.js");
        }
    });
    focList.add(new FileOutConfig("/templates/list.jsp.vm") {
        @Override
        public String outputFile(TableInfo tableInfo) {
            return getGeneratorViewPath(viewOutputDir, tableInfo, "List.jsp");
        }
    });*/
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

    // 执行生成
        mpg.execute();
    }

/**
 * 获取配置文件
 *
 * @return 配置Props
 */
private static Properties getProperties() {
    // 读取配置文件
    Resource resource = new ClassPathResource("application-dev.properties");
    Properties props = new Properties();
    try {
        props = PropertiesLoaderUtils.loadProperties(resource);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return props;
}

/**
 * 页面生成的文件名
 */
private static String getGeneratorViewPath(String viewOutputDir, TableInfo tableInfo, String suffixPath) {
    String name = StringUtils.firstToLowerCase(tableInfo.getEntityName());
    String path = viewOutputDir + "/" + name + "/" + name + suffixPath;
    File viewDir = new File(path).getParentFile();
    if (!viewDir.exists()) {
        viewDir.mkdirs();
    }
    return path;
}
}

二.springboot全局日志管理

     今天我们使用AOP去对我们的所有请求进行一个统一处理

     在pom.xml文件中导入下面

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

然后我们新建一个Aspect去对我们的所有Controller进行一个日志拦截。在SPringBoot中我们使用AOP也是很简单的,只需要在类上加上一个@Aspect的注解就好了,然后通过@Component注解到我们的Spring容器中去。我们新建一个包com.majiaxueyuan.log专门用来放我们的日志记录,代码如下

@Aspect
@Component
public class MjxyLogAspect {
private  final Logger logger = LoggerFactory.getLogger(getClass()); 
@Pointcut("execution(public * com.majiaxueyuan.controller..*.*(..))")
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
log.info("URL : " + request.getRequestURL().toString());
log.info("HTTP_METHOD : " + request.getMethod());
log.info("IP : " + request.getRemoteAddr());
Enumeration<String> enu = request.getParameterNames();
while (enu.hasMoreElements()) {
String name = (String) enu.nextElement();
log.info("name:{},value:{}", name, request.getParameter(name));
}
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
log.info("RESPONSE : " + ret);
}
}

 对还需要log4j的一个配置文件

在src/main/resources/下创建一个log4j.properties的文件(网上有)

 ### 设置###
log4j.rootLogger = debug,stdout,D,E

### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

三.定时任务

@Component
public class ScheduledTest {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

@Scheduled(fixedRate = 2000)
public void Schedule() {
System.out.println("码家学院提示你==》现在时间:" + dateFormat.format(new Date()));
}
}

另外我们需要在主函数启动类上开启定时器

@SpringBootApplication
@EnableScheduling
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

四.springboot实现异步

       这个和定时器差不多,启动加上@EnableAsync ,只需要在我们需要异步的方法上面加上@Async注解在启动类上加                    @EnableAsync.就可以了。

五。springboot在application.properties的自定义参数的获取

      application.properties

name=majiaxueyuan

      获取方式(加@Value{"${参数名字}"})

@Value("${name}")
private String name;
@ResponseBody
@RequestMapping("/getValue")
public String getValue() {
return name;
}

六.SpringBoot自定义启动端口+访问路径

server.port=9090
server.context-path=/springboot

六.SpringBoot配置文件yml

         下面讲一下SpringBoot中另外一种格式的配置文件,名为application.yml的配置文件,这种配置文件更方便我们使用,有提   示功能,而且SpringBoot也是默认去读取这个格式的配置文件,我们这里改变一下配置文件的风格。(这里我通过对比xml文件讲解)

       xml配置文件

server.port=9090
server.context-path=/springboot

spring.datasource.url=jdbc:mysql://localhost:3306/springboot_mjxy
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis.mapper-locations=classpath:mapper/*.xml
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
name=majiaxueyuan

      yml配置文件

server:
 port: 80
 context-path: /springboot
spring:
 datasource:
   username: root
   password: admin
   url: jdbc:mysql://localhost:3306/springboot_mjxy?characterEncoding=utf8
 thymeleaf:
   cache: false
   mode: LEGACYHTML5
   prefix: classpath:/templates/
   suffix: .html

    一般需要安装sts.

七.多环境区分

     我们可以创建多个配置文件,只需要在源配置文件上面增加下面的一个配置

server:
 port: 80
 context-path: /springboot
spring:
 profiles:
   active: lx
 datasource:
   username: root
   password: admin
   url: jdbc:mysql://localhost:3306/springboot_mjxy?characterEncoding=utf8
 thymeleaf:
   cache: false
   mode: LEGACYHTML5
   prefix: classpath:/templates/
   suffix: .html

这样系统就会优先去扫描配置文件是application-lx.yml的配置文件

八.springboot的部署

在pom.xml文件中加入添加springboot的maven插件

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>

项目右键-->Run As..-->Maven Build    在Goals:clean backage  ->run

在target/下产生该项目jar包

将该jar包传到linux系统中,

输入:输入命令:java -jar springboot-0.0.1-SNAPSHOT.jar启动项目。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值