Skip to content

springboot常用介绍 ​

官方文档:

springbootGitHub地址:https://github.com/spring-projects/spring-boot springboot官方文档:https://spring.io/guides/gs/spring-boot/

一、通过jar命令启动jar包 ​

pom增加插件编译,在spring boot2.3之前

xml
<build>
<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
</plugins>
</build>

pom增加插件编译,在spring boot2.3之后

xml
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <!--需要加这个,不然打包镜像找不到启动文件-->
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <fork>true</fork>
        <addResources>true</addResources>
    </configuration>
</plugin>

二、war包的形式放入tomcat容器 ​

1、在pom.xml中将打包形式 jar 修改为war

2、修改启动类

java
@SpringBootApplication
public class StartApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(StartApplication.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(StartApplication.class, args);
    }
}

3、打包项目,启动tomcat

三、获取jar包的路径 ​

java
// jar包获取可能会出现file:/字符
//第一种
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()) path = new File("");
System.out.println(path.getAbsolutePath());
//第二种
System.out.println(System.getProperty("user.dir"));
//第三种
String path1 = ClassUtils.getDefaultClassLoader().getResource("").getPath();
System.out.println(URLDecoder.decode(path1, "utf-8"));
//第四种
String path2 = ResourceUtils.getURL("classpath:").getPath();
System.out.println(path2);
//第五种
ApplicationHome h = new ApplicationHome(getClass());
File jarF = h.getSource();
System.out.println(jarF.getParentFile().toString());

四、springboot上传大小限制 ​

有两种方式解决 1、通过配置文件 2、加一个bean的管理(不推荐)

java
@Bean
public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory multipartConfigFactory = new MultipartConfigFactory();
    multipartConfigFactory.setMaxFileSize(1024*1024*10);
    multipartConfigFactory.setMaxRequestSize(1024*1024*10);
    return multipartConfigFactory.createMultipartConfig();
}

五、springboot的@ComponentScan注解 ​

@SpringBootApplication注解包含了@ComponentScan,springboot启动的时候会默认扫描当前启动类包下所有的bean(包含子目录)

六、springboot多模块扫包问题 ​

springboot启动的时候会默认扫描当前启动类包下所有的bean(包含子目录),但是由于多个子项目下的包路径可能不一样,会导致扫不到相应的bean。 两种解决方案: 1、修改@SpringBootApplication注解,把包路径往前,@SpringBootApplication(scanBasePackages="com.lcy.filesystem") 2、通过@Import注解引入子项目配置类,例如: @Import(Servicefiguration.class)

七、spring在创建完bean以后的回调方法 ​

bean类实现InitializingBean接口,并且实现afterPropertiesSet方法,这个方法就是初始化bean以后回调的方法