注解
1.@Value
2.@Bean
3.@ComponentScan
2.Spring Boot开发
1.打包Spring Boot应用
Spring Boot自带一个更简单的spring-boot-maven-plugin
插件用来打包,我们只需要在pom.xml
中加入以下配置:
<project ...>
...
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.瘦身Spring Boot应用
1.使用spring-boot-thin-launcher
修改<build>
-<plugins>
-<plugin>
,给原来的spring-boot-maven-plugin
增加一个<dependency>
如下:
<project ...>
...
<build>
<finalName>awesome-app</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-thin-layout</artifactId>
<version>1.0.27.RELEASE</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
不需要任何其他改动了,我们直接按正常的流程打包,执行mvn clean package
,观察target
目录最终生成的可执行awesome-app.jar
,只有79KB左右。
这个spring-boot-thin-launcher
在启动时搜索的默认目录是用户主目录的.m2
,我们也可以指定下载目录,例如,将下载目录指定为当前目录:
$ java -Dthin.root=. -jar xxx-app.jar
预热
java -Dthin.dryrun=true -Dthin.root=. -jar awesome-app.jar
2. 亲测可用
-
正常编译 Jar 包, 解压出lib文件夹
-
修改 pom.xml 配置,编译出不带 lib 文件夹的 Jar 包
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <!--main入口 自己修正--> <mainClass>com.cgp.jar.SpringBootJarApplication</mainClass> <layout>ZIP</layout> <includes> <include> <groupId>nothing</groupId> <artifactId>nothing</artifactId> </include> </includes> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
配置完成后,再次执行编译
生成的 Jar 包体积明显变小
- 运行编译后的 Jar 包 将解压出来的lib文件夹、新编译的jar包放在同一个目录, 运行下面命令 就能成功运行
java -Dloader.path=lib -jar spring-boot-jar-0.0.1-SNAPSHOT.jar
3.使用Actuator
而Spring Boot已经内置了一个监控功能,它叫Actuator。
使用Actuator非常简单,只需添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
1.Spring开发
1.IoC原理
Spring提供的容器又称为IoC容器,什么是IoC?
IoC全称Inversion of Control,直译为控制反转。那么何谓IoC?在理解IoC之前,我们先看看通常的Java组件是如何协作的。
依赖注入方式
我们从代码可以看到,依赖注入可以通过set()
方法实现。但依赖注入也可以通过构造方法实现。
Spring的IoC容器同时支持属性注入和构造方法注入,并允许混合使用。
无侵入容器
在设计上,Spring的IoC容器是一个高度可扩展的无侵入容器。所谓无侵入,是指应用程序的组件无需实现Spring的特定接口,或者说,组件根本不知道自己在Spring的容器中运行。这种无侵入的设计有以下好处:
- 应用程序组件既可以在Spring的IoC容器中运行,也可以自己编写代码自行组装配置;
- 测试的时候并不依赖Spring容器,可单独进行测试,大大提高了开发效率。
特殊符号处理
1.把<>进行转义 ‘< ;’ > ;
2.把带特殊符号内容写到 CDATA[]