zoukankan      html  css  js  c++  java
  • springboot项目1——初步使用

    new project

    出了利用ide,还可以通过https://start.spring.io/ , 或者使用maven命令mvn archetype:generate -DgroupId=org.conan.websocket -DartifactId=websocketServer -DarchetypeArtifactId=maven-archetype-webapp

    pom文件配置

    1.starter-parent
    它可以提供dependency management,也就是说依赖管理,引入以后在申明其它dependency的时候就不需要version了。

    <!-- spring boot parent节点,引入这个之后,在下面和spring boot相关的就不需要引入版本了; -->  
        <parent>  
           <groupId>org.springframework.boot</groupId>  
           <artifactId>spring-boot-starter-parent</artifactId>  
           <version>1.3.3.RELEASE</version>  
        </parent> 
    

    2.开发web工程,引入spring-boot-starter-web

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

    会下载并引入整个springframework依赖,以及autoconfigure、logging、slf4j、jackson、tomcat等web项目需要的东西。

    idea工具下,.iml文件可以看到引入的依赖包

    3.为了使用maven打包,配置插件

        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin </artifactId>
                    <executions>
                        <execution>
                            <goals>
                                <goal>repackage</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    

    并指明打包类型<packaging>jar</packaging>

    常用starter模块

    1)spring-boot-starter
    这是Spring Boot的核心启动器,包含了自动配置、日志和YAML。
    2)spring-boot-starter-actuator
    帮助监控和管理应用。
    3)spring-boot-starter-amqp
    通过spring-rabbit来支持AMQP协议(Advanced Message Queuing Protocol)。
    4)spring-boot-starter-aop
    支持面向方面的编程即AOP,包括spring-aop和AspectJ。
    5)spring-boot-starter-artemis
    通过Apache Artemis支持JMS的API(Java Message Service API)。
    6)spring-boot-starter-batch
    支持Spring Batch,包括HSQLDB数据库。
    7)spring-boot-starter-cache
    支持Spring的Cache抽象。
    8)spring-boot-starter-cloud-connectors
    支持Spring Cloud Connectors,简化了在像Cloud Foundry或Heroku这样的云平台上连接服务。
    9)spring-boot-starter-data-elasticsearch
    支持ElasticSearch搜索和分析引擎,包括spring-data-elasticsearch。
    10)spring-boot-starter-data-gemfire
    支持GemFire分布式数据存储,包括spring-data-gemfire。
    11)spring-boot-starter-data-jpa
    支持JPA(Java Persistence API),包括spring-data-jpa、spring-orm、Hibernate。
    12)spring-boot-starter-data-mongodb
    支持MongoDB数据,包括spring-data-mongodb。
    13)spring-boot-starter-data-rest
    通过spring-data-rest-webmvc,支持通过REST暴露Spring Data数据仓库。
    14)spring-boot-starter-data-solr
    支持Apache Solr搜索平台,包括spring-data-solr。
    15)spring-boot-starter-freemarker
    支持FreeMarker模板引擎。
    16)spring-boot-starter-groovy-templates
    支持Groovy模板引擎。
    17)spring-boot-starter-hateoas
    通过spring-hateoas支持基于HATEOAS的RESTful Web服务。
    18)spring-boot-starter-hornetq
    通过HornetQ支持JMS。
    19)spring-boot-starter-integration
    支持通用的spring-integration模块。
    20)spring-boot-starter-jdbc
    支持JDBC数据库。
    21)spring-boot-starter-jersey
    支持Jersey RESTful Web服务框架。
    22)spring-boot-starter-jta-atomikos
    通过Atomikos支持JTA分布式事务处理。
    23)spring-boot-starter-jta-bitronix
    通过Bitronix支持JTA分布式事务处理。
    24)spring-boot-starter-mail
    支持javax.mail模块。
    25)spring-boot-starter-mobile
    支持spring-mobile。
    26)spring-boot-starter-mustache
    支持Mustache模板引擎。
    27)spring-boot-starter-redis
    支持Redis键值存储数据库,包括spring-redis。
    28)spring-boot-starter-security
    支持spring-security。
    29)spring-boot-starter-social-facebook
    支持spring-social-facebook
    30)spring-boot-starter-social-linkedin
    支持pring-social-linkedin
    31)spring-boot-starter-social-twitter
    支持pring-social-twitter
    32)spring-boot-starter-test
    支持常规的测试依赖,包括JUnit、Hamcrest、Mockito以及spring-test模块。
    33)spring-boot-starter-thymeleaf
    支持Thymeleaf模板引擎,包括与Spring的集成。
    34)spring-boot-starter-velocity
    支持Velocity模板引擎。
    35)spring-boot-starter-web
    支持全栈式Web开发,包括Tomcat和spring-webmvc。
    36)spring-boot-starter-websocket
    支持WebSocket开发。
    37)spring-boot-starter-ws
    支持Spring Web Services。

    Spring Boot应用启动器面向生产环境的还有2种,具体如下:
    1)spring-boot-starter-actuator
    增加了面向产品上线相关的功能,比如测量和监控。
    2)spring-boot-starter-remote-shell
    增加了远程ssh shell的支持。

    最后,Spring Boot应用启动器还有一些替换技术的启动器,具体如下:
    1)spring-boot-starter-jetty
    引入了Jetty HTTP引擎(用于替换Tomcat)。
    2)spring-boot-starter-log4j
    支持Log4J日志框架。
    3)spring-boot-starter-logging
    引入了Spring Boot默认的日志框架Logback。
    4)spring-boot-starter-tomcat
    引入了Spring Boot默认的HTTP引擎Tomcat。
    5)spring-boot-starter-undertow
    引入了Undertow HTTP引擎(用于替换Tomcat)。

    运行方式

    通过主类启动。

    jar包启动,通过命令行设置属性值
    java -jar xxx.jar --server.port=8888覆盖配置文件

    通过使用mvn spring-boot:run命令利用spring boot框架内置的tomcat运行spring boot开发的web应用。
    https://blog.csdn.net/qwfys200/article/details/79983170
    idea中右键选择edit configuration 打开run configuration,左侧选maven,右侧命名,选定项目路径,command line里输入spring-boot:run ,然后Apply,最后点击Run。
    eclipse中右键project– Run as – Maven build –在Goals里输入spring-boot:run ,然后Apply,最后点击Run。

    热部署

    热部署就是在应用正在运行的时候升级软件,不需要重启服务
    开发过程中,修改部分代码无需反复进行服务重启,能大大提升开发效率
    https://412887952-qq-com.iteye.com/blog/2291518

    方式一:
    导入spring-boot-devtools模块

     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
    

    详见https://www.cnblogs.com/lspz/p/6832358.html
    https://blog.csdn.net/Oujenny/article/details/80355035
    https://412887952-qq-com.iteye.com/blog/2300313

    方式二:
    spring loaded也可实现修改类文件的热部署
    仅适用于用mvn spring-boot:run 启动项目的情况。
    或者,例如以下的启动參数:-javaagent:springloaded-1.2.7.RELEASE.jar -noverify,tomcat下改动该文件夹下的catalina.bat: set JAVA_OPTS=-javaagent:springloaded-1.2.0.RELEASE.jar -noverify可以检測tomcat下部署的webapp,在不重新启动tomcat的情况下。实现应用的热部署。
    https://github.com/spring-projects/spring-loaded

    方式三:
    Intellij热部署插件JRebel

    src/main/resouces/application.properties常用配置

    ########################################################
    ###EMBEDDED SERVER CONFIGURATION (ServerProperties)
    ########################################################
    #server.port=8080
    #server.address= # bind to a specific NIC
    #server.session-timeout= # session timeout in seconds
    #the context path, defaults to '/'
    #Spring boot默认是/ ,这样直接通过http://ip:port/就可以访问到index页面,修改为http://ip:port/spring-boot 路径。更高版本的springboot,在新的版本中配置需改为server.servlet.context-path=/XXXXXXX;
    #server.context-path=/spring-boot
    #server.servlet-path= # the servlet path, defaults to '/'
    #server.tomcat.access-log-pattern= # log pattern of the access log
    #server.tomcat.access-log-enabled=false # is access logging enabled
    #server.tomcat.protocol-header=x-forwarded-proto # ssl forward headers
    #server.tomcat.remote-ip-header=x-forwarded-for
    #server.tomcat.basedir=/tmp # base dir (usually not needed, defaults to tmp)
    #server.tomcat.background-processor-delay=30; # in seconds
    #server.tomcat.max-threads = 0 # number of threads in protocol handler
    #server.tomcat.uri-encoding = UTF-8 # character encoding to use for URL decoding
    

    获取环境变量以及配置属性

    被Spring管理的类,实现接口 EnvironmentAware 重写方法 setEnvironment 就可以在工程启动时,获取到系统环境变量和application配置文件中的变量。

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.bind.RelaxedPropertyResolver;
    import org.springframework.context.EnvironmentAware;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.env.Environment;
    
    @Configuration
    public class MyEnvironmentAware implements EnvironmentAware {
    
    
        //注入application.properties中指定的属性到指定变量中.
        @Value("${spring.datasource.url}")
        private String myUrl;
    
        /**
         * 在系统启动的时候被执行。
         * @param environment
         */
        @Override
        public void setEnvironment(Environment environment) {
            //打印注入的属性信息.
            System.out.println("myUrl="+myUrl);
    
            //通过 environment 获取到系统属性.
            System.out.println(environment.getProperty("JAVA_HOME"));
    
            //通过 environment 同样能获取到application.properties配置的属性.
            System.out.println(environment.getProperty("spring.datasource.url"));
    
            //获取到前缀是"spring.datasource." 的属性列表值.
            RelaxedPropertyResolver relaxedPropertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource.");
    
            System.out.println("spring.datasource.url="+relaxedPropertyResolver.getProperty("url"));
            System.out.println("spring.datasource.driverClassName="+relaxedPropertyResolver.getProperty("driverClassName"));
        }
    }
    

    也可以用一个Controller来实现EnvironmentAware 达到获取环境变量和配置属性值。

    配置属性绑定到配置对象中

    通过@ConfigurationProperties 读取配置文件中的属性,直接绑定到对象属性中
    1.这个配置对象可能是被框架封装好的(多数情况),如DataSource:

    @Configuration
    public class DataSourceConfig {
    
        /**
         * 注入DruidDataSource,同时加载自定义配置项
         */
        @Bean(name = "druidDataSource")
        @Qualifier("druidDataSource")
        @ConfigurationProperties(prefix="spring.datasource")//以spring.datasource作为前缀的属性通过名字直接映射为对象的属性
        public DataSource getMyDataSource(){
            return new DruidDataSource();
        }
    
    }
    

    PS:需要指定配置文件名时:@ConfigurationProperties(prefix = "spring.datasource",locations = "classpath:applicatin1.properties")

    springboot 1.5.8 pom里面加了依赖,ConfigurationProperties注解已经不支持locations了,然后对象的属性值是空的。
    解决方法:在属性对象上面除了加一个@ConfigurationProperties注解外,再加个@PropertySource注解,并且不用再主类上加@EnableConfigurationProperties注解了

    2.也可以自定义配置类,如:

    /**
     * 以test.conf作为前缀的属性,通过名字直接映射绑定为对象的属性
     *
     */
    @ConfigurationProperties(prefix = "test.conf")
    @Data
    public class TestProperties {
        private String name;
        private String pass;
        private String url;
    
    }
    

    然后在启动类或其他@Configuration类(自动配置类)中加@EnableConfigurationProperties(TestProperties.class)注解即可,使用的时候注入进来即可使用
    参考这里

    多配置文件

    详见

    在环境中设定一个活动的配置文件:
    可以在参数中使用 java -Dspring.profiles.active=prod -jar springboot.jar
    或者java -jar springboot.jar --spring.profiles.active=prod
    或者在 application.properties 中使用 spring.profiles.active=prod

    @Profile("dev")表明只有Spring定义的Profile为dev时才会实例化DevEmailService这个类。@Profile({"default", "dev"})表示dev是默认环境。

    另外,还可以利用maven profile来切换环境参数
    打包指定的环境通过-P 参数:mvn package -P <env>

    在 Spring Boot 启动的时候运行一些特定的代码

    可以实现接口 ApplicationRunner 或者 CommandLineRunner,这两个接口实现方式一样,它们都只提供了一个 run 方法

    /**
     * 服务启动执行
     * @Order 注解的执行优先级是按value值从小到大顺序。
     */
    
    @Component
    @Order(value=1)
    public class MyStartupRunner1 implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            System.out.println(">>>>>>>>>>>>>>>服务启动执行,MyStartupRunner1 执行加载数据等操作 11111111 <<<<<<<<<<<<<");
        }
    }
    

    Spring Boot如何使用Junit

    pom.xml添加:

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

    编写测试类(包最好同名,类名起为测试的service类名+Test)
    用到@RunWith(SpringRunner.class)、@SpringApplicationConfiguration(classes = App.class)指定启动类,Web项目,Junit需要模拟ServletContext,因此需要加上@WebAppConfiguration。

    .SpringBoot启动时的Banner设置

    不喜欢这个输出怎么关?
    1.在application.proerpties进行banner的显示和关闭:
    spring.main.show-banner=false
    2.启动类main方法中:

    SpringApplication application = new SpringApplication(App.class);
            /*
             * Banner.Mode.OFF:关闭;
             * Banner.Mode.CONSOLE:控制台输出,默认方式;
             * Banner.Mode.LOG:日志输出方式;
             */
             application.setBannerMode(Banner.Mode.OFF); 
             application.run(args); 
    

    也可以修改,springboot banner中文在线生成工具

    出现未注入情况的可能原因

    Spring Boot默认扫描启动类同包以及子包下的注解,不在那些包下的类如SpringUtil,如果想交给spring容器管理,首先使用@Component注解该类,然后需要在启动类里使用

        @Bean
        public SpringUtil springUtil(){return new SpringUtil();}
    

    的方式进行注册(或者通过@Import(value={SpringUtil.class})导入,在SpringUtil不需要添加@Component注解 )。这样会有些麻烦,所以spring提供了@ComponentScan注解指定要扫描的包以及要扫描的类。
    如:@ComponentScan(basePackages={"com.cashew","org.cashew"})
    如果此时启动类所在的包没有写进去,那么就不会扫描!

    Spring Boot 打成的 jar 和普通的 jar 有什么区别

    Spring Boot 项目一般使用spring-boot-maven-plugin插件打包,最终打包成的 jar 是可执行 jar ,这种 jar 可以直接通过 java -jar xxx.jar 命令来运行,这种 jar 不可以作为普通的 jar 被其他项目依赖,即使依赖了也无法使用其中的类。

    Spring Boot 的 jar 无法被其他项目依赖,主要还是他和普通 jar 的结构不同。普通的 jar 包,解压后直接就是包名,包里就是我们的代码,而 Spring Boot 打包成的可执行 jar 解压后,在 BOOT-INFclasses 目录下才是我们的代码,因此无法被直接引用。如果非要引用,可以在 pom.xml 文件中增加配置,将 Spring Boot 项目打包成两个 jar ,一个可执行,一个可引用。

    给springboot的jar包减肥

    默认sp项目打依赖包在BOOT-INFlib下,有时候为了提高打包的效率,可以将项目的第三方依赖包、以及配置文件都提取到jar包外进行统一管理。
    build模块配置如下可实现:

     <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <!--编译、打包时排除配置文件-->
                    <excludes>
                        <exclude>**/*.properties</exclude>
                        <exclude>**/*.xml</exclude>
                        <exclude>**/*.yml</exclude>
                    </excludes>
                    <filtering>true</filtering>
                </resource>
            </resources>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <fork>true</fork>
                        <skip>true</skip>
                    </configuration>
                </plugin>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <configuration>
                        <archive>
                            <manifest>
                                <addClasspath>true</addClasspath>
                                <classpathPrefix>lib/</classpathPrefix>
                                <useUniqueVersions>false</useUniqueVersions>
    							 <!--mainClass指定-->
                                <mainClass>com.configure.Application</mainClass>
                            </manifest>
                            <manifestEntries>
                                <Class-Path>./</Class-Path>
                            </manifestEntries>
                        </archive>
                        <excludes>
                            <exclude>*.properties</exclude>
                            <exclude>*.yml</exclude>
                            <exclude>*.xml</exclude>
                            <exclude>config/**</exclude>
                        </excludes>
                    </configuration>
                </plugin>
    
            </plugins>
        </build>
    

    META-INF/MANIFEST.MF文件会指定依赖包的位置,如:Class-Path: ./ lib/spring-boot-starter-web-2.1.6.RELEASE.jar lib/HdrHistogram-2.1.9.jar lib/LatencyUtils-2.0.3.jar
    至于核心配置文件,可通过命令参数的方式来指定,如:java –jar -Dspring.config.location=xxx/xxx/xxxx.properties xxxx.jar

    至于其他一些业务上的配置文件,如数据源配置文件,公共资源定义配置文件(常量,FTP信息等),quartz定时器,日志等配置文件我们如何去提取出来并确保能在代码中引用到呢?
    可以利用@PropertySource注解方式让项目能够引用到jar包外部的配置文件。

    @PropertySource的value有两个值,第一个是classpath下config目录下的数据源配置文件,第二个则是根据spring.profiles.path动态获取的目录,设置属性ignoreResourceNotFound=true意思是假如根据前面一个路径没有找到相关配置文件,则根据第二个路径去找。

    1. 在springboot核心配置文件里定义spring.profiles.path配置项,值指向所有配置文件统一放置的目录(包含核心文件)。
    2. 核心配置文件里里定义如日志配置文件logging.config=${spring.profiles.path}/logback-spring.xml

    关于yml

    1.Springboot 之 自定义配置文件及读取配置文件注意:配置文件中的字符串不要有下划线 .配置中 key不能带下划线
    2.不能大写字母开头
    3.变量引用,参考:https://www.cnblogs.com/haycheng/p/13299183.html

    测试相关

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = AppStarter.class)
    public class Test1 {
    
    }
    

    记录Spring Boot大坑一个,在bean中如果有@Test单元测试,不会注入成功
    记录Spring Boot大坑一个,在bean中如果有@Test单元测试,不会注入成功
    记录Spring Boot大坑一个,在bean中如果有@Test单元测试,不会注入成功
    记录Spring Boot大坑一个,在bean中如果有@Test单元测试,不会注入成功
    org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type

    报错记录

    springboot启动报错:This can also happen if you are @ComponentScanning a springframework package
    SpringBoot启动类型java 文件不能直接放在main/java文件夹下,必须要建一个包把他放进去,一般是放在com.cashew这样的包名里

  • 相关阅读:
    sqlserver查询某个数据库有多少个表 ,存过,函数,视图
    C# 金额转为大写金额
    C# TextBox中只能输入数字的几种常用方法(C#)
    C# 设置Excel单元格属性
    MS SQL 维护小记
    webapi demo
    远程 TeamViewer
    https://github.com/
    C# Fun 类似委托
    技术点文章收集
  • 原文地址:https://www.cnblogs.com/cashew/p/10467914.html
Copyright © 2011-2022 走看看