1.SpringBoot简介
1.1SpringBoot概述
Spring Boot 是在 Spring 的基础上提供的一套全新的开源框架,其目的是为了简化 Spring 应用的搭建和开发过程。Spring Boot 去除了大量的 XML 配置文件,简化了复杂的依赖管理。
Spring Boot 具有 Spring 一切优秀特性,Spring 能做的事,Spring Boot 都可以做,而且使用更加简单,功能更加丰富,性能更加稳定而健壮。
在没有SpringBoot的时候我们创建基于Spring框架的应用程序,或者是整合SpringMVC、MyBatyis等等其他的框架时候,往往都需要先导入很多的依赖包,在导入依赖的时候少了/版本不匹配,都会造成创建应用程序/整合其他框架失败。除过导入依赖麻烦,还需要配置很多相关的配置文件【applicationContext.xml /MyBatis-config.xml..... 】。在部署创建完成好的应用程序时,还得配置好服务器环境。所以在以前没有SpringBoot的时候,我们对java EE程序的开发都是比较笨重的开发,需要繁多的配置,带来低下的开发效率和复杂的部署流程,还有第三方技术集成难度大。
因此上SpringBoot的出现实际上就是用来简化我们对java EE程序的开发,帮助我们快速的创建出基于Spring的应用程序。
1.导入依赖包方便
2.减少配置文件
3.配置服务器环境
1.2 SpringBoot的优点
1.快速创建独立运行的Spring项目以及与主流框架集成
2.使用嵌入式的Servlet容器,应用无需打成WAR包
3.starters自动依赖与版本控制
4.大量的自动配置,简化开发,也可修改默认值
5.无需配置XML,无代码生成,开箱即用
6.准生产环境的运行时应用监控
7.与云计算的天然集成
2.SpringBoot初体验
需求:浏览器发送hello请求,服务器接受请求并处理,响应Hello World字符串。
(1)新建项目,选择Spring Initializr,选好对应配置
(2)在pom.xml文件中配置开发Javaweb程序的启动器
可以帮助我们将开发基于Spring的web应用程序的所有依赖包全部自动导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
(3)在src/main/java下创建控制器类
@Controller
public class HelloController {
@RequestMapping("/hello")
@ResponseBody
public String helloString(){
return "hello,springboot";
}
}
由于我们自己创建的控制器类与SpringBoot的主类不在同一个包中
控制器类--- com.weiwei.springbootdemo1.controller
SpringBoot的主类--- com.weiwei.springbootdemo1.sss
我们需要给主类上添加
@ComponentScan(basePackages = "com.wangxing.springboot.demo1")
如果我们自己创建的控制器类与SpringBoot的主类在同一个包中,那么这个注解不用加。
(4)运行主类中的主方法,应用程序自动部署,内嵌的Servlet容器自动启动
(5)浏览器测试:localhost:8080/hello
【注意】:
不同包中不加扫描包会报错
@SpringBootApplication
@ComponentScan(basePackages = "com.weiwei.springbootdemo1")
public class Springbootdemo1Application {
public static void main(String[] args) {
SpringApplication.run(Springbootdemo1Application.class, args);
}
}
总结下,主类当前所在的包,会被自动扫描,其他类如果不在主类当前包下,就需要
@ComponentScan(basePackages = "有注解的大包")注解。
这样就不需要
(6)打包, 通过java -jar xxxxx.jar命令来执行
在当前项目的target目录下得到“项目名称-版本号.jar”
springbootdemo1-0.0.1-SNAPSHOT.jar
将这个jar包复制出去,编写一个与之对应的批处理文件【内容:java -jar springbootdemo1-0.0.1-SNAPSHOT.jar】,双击就可运行
3. JavaConfig配置类
之前SSM框架程序配置是需要依赖XML配置文件,现在主要使用基于Java代码和Annotation注解的方式完成配置,减少配置文件和配置内容。
任何一个标注了@Configuration的Java类定义都是一个 JavaConfig 配置类。
任何一个标注了@Bean的方法,其返回值将作为一个bean定义注册到Spring的IoC容器,方法名将默认成为该bean定义的id属性。
(1)表达形式层面
基于 XML 的配置方式是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="stubean" class=" com.weiwei.springbootdemo1.bean.StudentBean"></bean>
创建StudentBean对象
</beans>
基于Java代码和Annotation注解的方式取代基于 XML 的配置方式
@Configuration
public class StudentConfig {
//其返回值将作为一个bean定义注册到Spring的IoC容器,方法名将默认成为该bean定义的id属性
@Bean
public StudentBean studentbean() {
return new StudentBean();
}
}
(2)构造方法注入
public class PersonBean {
public void testPerson(){
System.out.println("person的实例方法");
}
}
public class StudentBean {
private PersonBean personBean;
public StudentBean(PersonBean personBean) {
this.personBean = personBean;
}
public void testStudent(){
personBean.testPerson();
System.out.println("student的实例方法");
}
基于 XML 的配置方式是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person "class=" com.weiwei.springbootdemo1.bean.PersonBean"/>
<bean id="student" class=" com.weiwei.springbootdemo1.bean.StudentBean ">
<constructor-arg name="personBean" ref="person" />
</bean>
</beans>
基于Java代码和Annotation注解的方式取代基于 XML 的配置方式
@Configuration
public class StudentConfig {
@Bean
public PersonBean personBean(){
return new PersonBean();
}
@Bean
public StudentBean studentbean() {
return new StudentBean(personBean());
}
}
测试:
@Test
void testStudent1(){
AnnotationConfigApplicationContext ac =
new AnnotationConfigApplicationContext(StudentConfig.class);
StudentBean stu = ac.getBean("studentbean", StudentBean.class);
stu.testStudent();
}
输出:
person的实例方法
student的实例方法
(3)set方法注入
基于 XML 的配置方式是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="per" class=" com.weiwei.springbootdemo1.bean.PersonBean"/>
<bean id="stu" class=" com.weiwei.springbootdemo1.bean.StudentBean">
<property name="personBean" ref="per"/>
</bean>
</beans>
基于Java代码和Annotation注解的方式取代基于 XML 的配置方式
@Configuration
public class StudentConfig {
@Bean
public PersonBean personBean(){
return new PersonBean();
}
//set方法注入
@Bean
public StudentBean studentBean(){
StudentBean studentBean = new StudentBean();
studentBean.setPersonBean(personBean());
return studentBean;
}
补充:
@Configuration(默认proxyBeanMethods=true),配置类里面使用@Bean标注在方法上给容器注册组件,默认是单实例的,即外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象。
反之,@Configuration(proxyBeanMethods=false),每次调用这个组件注册方法,获取的对象都是一个新的对象。
比如用户对象和宠物对象,用户对象里面需要宠物对象,如果是true,那么最后用户对象里面拿到的宠物对象就是容器创建好的那个宠物对象,如果是false,也就是说拿到的宠物对象是一个新的对象,不等于容器创建的那个对象。
true的时候,叫Full模式。配置类组件之间有依赖关系,方法会调用得到之前单实例组件,用Full模式。
false的时候,叫Lite模式。配置类组件之间无依赖关系,用Lite模式加速容器启动过程,减少判断。
4. 代替XML的配置方式的常见注解
4.1 @ComponentScan
@ComponentScan(basePackages="基础包名称")【主类上】 配置自动扫描包,将java类上带有@Component("自定义名称"),@Repository("自定义名称"),@Service("自定义名称"),@Controller注解的java类实例化。
代替了xml配置文件中<context:component-scan base-package="基础包名称"></context:component-scan>
4.2 @PropertySource和@PropertySources
@PropertySource("classpath:db.properties")读取从resources下xxxx.properties资源文件【有@Configuration的java类上,特别是数据源配置类】
代替了xml配置文件中<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
@PropertySources---加载resources下一组xxxx.properties资源文件
@PropertySources({
@PropertySource("classpath:1.properties"),
@PropertySource("classpath:2.properties"), ...
})
@PropertySource是Spring boot为了方便引入properties配置文件提供的一个注解,可以标注在SpringBoot的启动类上,还可以标注在配置类(使用@Configuration标注的类)上。使用@Value("${key}")取值。
标注在主类上
@SpringBootApplication
@PropertySource(value = "classpath:mydata.properties")
public class Springbootdemo1Application {
public static void main(String[] args) {
SpringApplication.run(Springbootdemo1Application.class, args);
}
}
控制类测试
@Controller
public class DataController {
@Value("${jdbc.username}")
private String username;
@RequestMapping("/test")
@ResponseBody
public void testUsername(){
System.out.println(username);//root
}
}
标注在配置类上
@Component
@Configuration
@PropertySource(value = "classpath:mydata.properties")
@Getter
public class DataConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
}
测试
@Autowired
private DataConfig dataConfig;
@Test
public void test1(){
System.out.println(this.dataConfig.getPassword());//123456
}
4.3 lombok插件
Lombok项目是一种自动接通你的编辑器和构建工具的一个Java库。不用再一次写额外的getter或者equals方法。由此可以看出,lombok会帮我们自动生成getter和euqals方法,但是更有意思的是,当我们的变量发生改变时,我们不再需要修改对的getter、setter方法,lombok帮我们在运行的过程中自动生成上述方法,编码更灵活。
所以,使用lombok的优点:
1、简化long冗余的javabean代码;
2、提高执行效率
@Setter :在JavaBean或类JavaBean中使用,使用此注解会生成对应的setter方法;
@Getter:在JavaBean或类JavaBean中使用,使用此注解会生成对应的getter方法;
@ToString:在JavaBean或类JavaBean中使用,使用此注解会自动重写对应的toStirng方法;
@NoArgsConstructor:在JavaBean或类JavaBean中使用,使用此注解会生成对应的无参构造方法;
@Data:在JavaBean或类JavaBean中使用,这个注解包含范围最广,它包含上述注解,即当使用当前注解时,会自动生成包含的所有方法;
@AllArgsConstructor:在JavaBean或类JavaBean中使用,使用此注解会生成对应的有参构造方法;
@Log(这是一个泛型注解,具体有很多种形式)
@EqualsAndHashCode:在JavaBean或类JavaBean中使用,使用此注解会自动重写对应的equals方法和hashCode方法;
例:
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@AllArgsConstructor
@ToString
public class UserBean {
private int userid;
private String username;
}
4.4 @Import 与 @ImportResource
在 XML 形式的配置中,我们通过 <import resource="XXX.xml"/> 的形式将多个分开的容器配置合到一个配置中,在 JavaConfig 形式的配置中,我们则使用 @Import 这个 Annotation 完成同样目的:
@ImportResource方式
其参数指定的是配置文件路径
@Import方式-------将多个分开配置类【@Configuration的java类】,合并到一个配置类中
其参数指定的是Class信息,也就是指向配置类
public class Test1 {
public void printMsg(String msg) {
System.out.println("test1 : " + msg);
}
}
public class Test2 {
public void printMsg(String msg) {
System.out.println("test2 : " + msg);
}
}
@Configuration
public class Test1Config {
@Bean
public Test1 test1() {
return new Test1();
}
}
@Configuration
public class Test2Config {
@Bean
public Test2 test2() {
return new Test2();
}
}
@Configuration
@Import({ Test1Config.class, Test2Config.class })
public class AppConfig {}
测试:
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Test1 test1 = (Test1) context.getBean("test1");
test1.printMsg("Hello test1");
Test2 test2 = (Test2) context.getBean("test2");
test2.printMsg("Hello test2");
目的主要就是我们项目搭建的时候要多使用这种分模块开发的方式,不要一个配置文件把所有的Bean都放在里面,尽量按某一个维度来分开,分开之后的聚合就是使用Import相关标签来实现。