Springboot
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
springboot=spring+springmvc
xml | @Confirguation |
---|---|
bean | @bean |
注意:
java配置@Confirguation注解加在类上,表示当前类为配置类
@bean加在方法上表示当前方法返回值是需要交由工厂管理的对象,方法名就是对象的名字
src/main/java
com.baizhi
entity
dao
service
Application.java 必须放置在主包内和子包同级
src/main/resources
application.yml
application.yaml
application.properties
配置文件放置在resources目录,名字必须叫application
src/test/java
src/test/resources
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>1.5.7.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
dependency>
dependencies>
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class,args);
}
}
@RestController
@RequestMapping("/test")
public class UserController {
@RequestMapping("/test")
public String test(){
return "hello springboot";
}
}
修改springboot的jar版本为1.5.7
@ComponentScan(basePackages = "com.baizhi.*")
@Configuration
@EnableAutoConfiguration
/*
* 组合注解:一个注解包含多个注解的功能
* @SpringBootApplication=@Configuration+@ComponentScan+@EnableAutoConfiguration
* @Configuration:加在类上声明当前类 为配置类
* @ComponentScan:组件扫描,将扫描到的类交由工厂管理
* @Repository
@Component
@Service
@Controller
@EnableAutoConfiguration:开启自动配置,一旦引入第三方的jar,springboot就可以帮你配制相关组件
*
* */
/*
* 组合注解@RestController=@Controller+ @ResponseBody
* 加在控制器类上表明当前类是控制器对象,并且返回json
*
* springboot默认的视图层模板不是jsp thymeleaf
* */
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>1.3.3version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.16version>
dependency>
#数据源类型 以及参数
spring:
datasource:
url: jdbc:mysql://localhost:3306/springboot
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
#mybatis相关配置 别名 mapper位置
mybatis:
type-aliases-package: com.baizhi.entity
mapper-locations: classpath:com/baizhi/mapper/*Mapper.xml
@SpringBootApplication
//指定dao位置从而创建dao的动态代理类
@MapperScan(basePackages = "com.baizhi.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class,args);
}
}
<dependency>
<groupId>org.apache.tomcat.embedgroupId>
<artifactId>tomcat-embed-jasperartifactId>
dependency>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
spring:
mvc:
view:
prefix: /
suffix: .jsp
#热部署
server
jsp-servlet:
init-parameters:
development: true
1.日志的级别:debug—info—warn–error 日志级别越低打印日志量越多,越详细
2.日志的分类: 父日志(根日志) 控制全局日志
子日志 某个包中的日志 子日志优先级高于父日志
3.Appender 为日志输出目的地,Log4j提供的appender有以下几种:
org.apache.log4j.ConsoleAppender(控制台),
org.apache.log4j.FileAppender(文件),
org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件),
org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件),
org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)
4.Layout:日志输出格式,Log4j提供的layout有以下几种
org.apache.log4j.HTMLLayout(以HTML表格形式布局),
org.apache.log4j.PatternLayout(可以灵活地指定布局模式),
org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串),
org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)
5.打印参数: Log4J采用类似C语言中的printf函数的打印格式格式化日志信息,如下:
%m 输出代码中指定的消息
%p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL
%r 输出自应用启动到输出该log信息耗费的毫秒数
%c 输出所属的类目,通常就是所在类的全名
%t 输出产生该日志事件的线程名
%n 输出一个回车换行符,Windows平台为“\r\n”,Unix平台为“\n”
%d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss ,SSS},输出类似:2002年10月18日 22 : 10 : 28 , 921
%l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。举例:
Testlog4.main(TestLog4.java: 10 )
//命名必须为logback.xml然后放置在resources目录
<configuration>
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern> [%p] [%d{yyyy-MM-dd HH:mm:ss}] %m %npattern>
layout>
appender>
<root level="info">
<appender-ref ref="stdout"/>
root>
<logger name="com.baizhi.mapper" level="DEBUG"/>
configuration>
1.使用日志
//构建logger对象
private static Logger logger= LoggerFactory.getLogger(UserServiceImpl.class);
//自定义日志
logger.debug("this is debug");
logger.info("this is info");
logger.warn("this is warn");
logger.error("this is error");
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.6version>
<scope>providedscope>
dependency>
@Accessors(chain = true) 用在类上支持set方法的链式调用
@AllArgsConstructor 用在类上提供全参构造
@Data 用在类上提供get set tostring noargs hashcode and equals
@Getter 用在类上提供get
@Setter 用在类上提供set
@AllArgsConstructor
@NoArgsConstructor
@ToString
@EqualsAndHashCode
构建配置文件 jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/springboot
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.userName=root
jdbc.password=root
@PropertySource(value = "classpath:/jdbc.properties")
public class JavaConf {
@Value("${jdbc.url}")
public String url;
@Value("${jdbc.password}")
public String password;
@Value("${jdbc.userName}")
public String userName;
@Value("${jdbc.driverClassName}")
public String driverClassName;
}
server.port=8989
jdbc.url=jdbc:mysql://localhost:3306/springboot
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.userName=root
jdbc.password=root
@ConfigurationProperties(prefix = "jdbc")
public class JdbcProp {
private String url;
private String userName;
private String password;
private String driverClassName;
}
@EnableConfigurationProperties(value = JdbcProp.class)
@Configuration
public class JavaConf {
@Autowired
JdbcProp jdbcProp;
@Bean
public DruidDataSource getDruidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(jdbcProp.getUrl());
druidDataSource.setUsername(jdbcProp.getUserName());
druidDataSource.setPassword(jdbcProp.getPassword());
druidDataSource.setDriverClassName(jdbcProp.getDriverClassName());
return druidDataSource;
}
}
总结:springboot在加载工厂的过程中,优先加载启动器中的相关代码,将相关的对象交由工厂管理,如果想动态的修改对象相关属性,可以采用属性注入的方式完成
//已经封装了junit 不需要再引入junit的jar
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
dependency>
@SpringBootTest(classes =App.class) //声明是springboot的测试类 并且指定入口类
@RunWith(SpringRunner.class) //在工厂环境下启动测试
public class UserTest {
@Autowired
UserMapper userMapper;
@Test
public void testUser(){
List<User> users = userMapper.queryAll();
for (User user : users) {
System.out.println(user);
}
}
}
乱码:get请求乱码,springboot内嵌tomcat为utf-8
post请求乱码
springboot启动器中配置
@Bean
@ConditionalOnMissingBean({CharacterEncodingFilter.class})
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
filter.setEncoding(this.properties.getCharset().name());
filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
return filter;
}
spring
http:
encoding:
charset: utf-8
force: true
@ConditionalOnMissingBean({MultipartResolver.class})
public StandardServletMultipartResolver multipartResolver() {
StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
multipartResolver.setResolveLazily(this.multipartProperties.isResolveLazily());
return multipartResolver;
}
spring:
http:
multipart:
#单个文件的最大值
max-file-size: 10Mb
#一次请求的最大值
max-request-size: 100MB
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<version>1.5.7.RELEASEversion>
dependency>
jar包部署注意两点,第一点是将webapp打包到MET-inf,第二点是使用1.4.2的spring-boot-maven-plugin
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<version>1.4.2.RELEASEversion>
<configuration>
<mainClass>com.baizhi.AppmainClass>
<layout>JARlayout>
configuration>
plugin>
plugins>
<resources>
<resource>
<directory>src/main/webappdirectory>
<targetPath>META-INF/resourcestargetPath>
<includes>
<include>**/**include>
includes>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/**include>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<excludes>
<exclude>**/*.javaexclude>
excludes>
resource>
resources>
1.引入依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-aopartifactId>
<version>1.5.7.RELEASEversion>
dependency>
2.开发切面通知切入点
@Pointcut(value = "execution(* com.baizhi.service.*.*(..))")
public void pt(){
}
// @Before("pt()")
// public void testBefore(JoinPoint joinPoint){
// //目标方法对象
// Signature signature = joinPoint.getSignature();
// //目标方法参数列表
// Object[] args = joinPoint.getArgs();
// //目标对象
// Object target = joinPoint.getTarget();
// System.out.println(signature);
// System.out.println(args);
// System.out.println(target);
//
// System.out.println("this is before advice");
// }
//
//
//
// @After("pt()")
// public void testAfter(JoinPoint joinPoint){
// //目标方法对象
// Signature signature = joinPoint.getSignature();
// //目标方法参数列表
// Object[] args = joinPoint.getArgs();
// //目标对象
// Object target = joinPoint.getTarget();
// System.out.println(signature);
// System.out.println(args);
// System.out.println(target);
//
// System.out.println("this is after advice");
// }
@Around("pt()")
public Object testAround(ProceedingJoinPoint proceedingJoinPoint){
Object proceed=null;
try {
//作用 放行执行目标方法 返回值是目标方法的返回值
proceed = proceedingJoinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return proceed;
}
}