springboot(使用)

springboot(使用)

springboot的自动配置是引入了started jar之后就自动集成了相应的框架,不做额外的代码覆盖的话就用这个框架的默认的配置,自动装配的框架都会

有默认配置(@EnableAutoConfiguration)(装配好配置好的文件类,默认的文件类

修改之后需要对build.gradle右键刷新才可

@Configuration 配置类

@Import导入类

@ComponentScan收集spring所有spring类包括@Configuration 搜索beans,并结合 @Autowired 构造器注入。

如果将主应用类放到根目录下,@componentScan不需要任何参数,即可搜集到所有( @Component , @Service , @Repository , @Controller 等)

@ImportResource 加载xml

EnableAutoConfiguration自动配置或 @SpringBootApplication添加到一个 @Configuration 类上来选择自动配置。

根据加载的jar依赖自动配置,而且自动配置@Configuration的类

@SpringBootApplication=@Configuration , @EnableAutoConfiguration 和 @ComponentScan

--debug启动可以看当前的自动配置

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})禁用自定义配置,排除相应主类即可

java -jar 运行jar

java -jar target/myproject-0.0.1-SNAPSHOT.jar

可以设置远程运行的jar包(开启远程调试),在本机调试

$ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \

-jar target/myproject-0.0.1-SNAPSHOT.jar

CommandLineRunne  命令行启动是指定在应用启动之后马上执行的代码(如果有多个可以设置执行顺序)实现这个接口即可

外化配置:

即参数的引用

使用@Value注解,可以直接将属性值注入到你的beans中  不必自己配置这个工具类springboot自己配置,单纯使用spring的话需要陪置

覆盖顺序:

Spring Boot使用一个非常特别的PropertySource次序来允许对值进行合理的覆盖,需要以下面的次序考虑属性:(越在上优先级越大)

1. 命令行参数

2. 来自于java:comp/env的JNDI属性

3. Java系统属性(System.getProperties())

4. 操作系统环境变量

5. 只有在random.*里包含的属性会产生一个RandomValuePropertySource

6. 在打包的jar外的应用程序配置文件(application.properties,包含YAML和profile变量)

7. 在打包的jar内的应用程序配置文件(application.properties,包含YAML和profile变量)

8. 在@Configuration类上的@PropertySource注解

9. 默认属性(使用SpringApplication.setDefaultProperties指定)

import org.springframework.stereotype.*

import org.springframework.beans.factory.annotation.*

@Component

public class MyBean {

@Value("${name}")

private String name;

// ...

}

注入随机值:

my.secret=${random.value}

my.number=${random.int}

my.bignumber=${random.long}

my.number.less.than.ten=${random.int(10)}

my.number.in.range=${random.int[1024,65536]}

可以通过命令行将参数放到spring环境中,也可以通过application.properties文件将配置放到spring环境中

属性文件可以配置多个,同名或不同名,在不同的路径优先级不同

1. 当前目录下的一个/config子目录

2. 当前目录

3. 一个classpath下的/config包

4. classpath根路径(root)

这个列表是按优先级排序的(列表中位置高的将覆盖位置低的)。

本配置文件可以用本配置文件的值(${})

自动装配的个性化覆盖,排除

覆盖,

1·重新注入相同的类(因为springboot在默认配置的时候用用的id就是根据类名来的,当我们用同样的类那么名字就自然一样,这样就覆盖了默认配置)

如果不想覆盖执行器的访问规则,你可以使用

@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)注解该bean,否则使用

@Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)注解该bean。

Spring MVC使用HttpMessageConverter接口转换HTTP请求和响应。合理的缺省值被包含的恰到好处(out of the box),例

如对象可以自动转换为JSON(使用Jackson库)或XML(如果Jackson XML扩展可用则使用它,否则使用JAXB)。字符串

默认使用UTF-8编码。

如果需要添加或自定义转换器,你可以使用Spring Boot的HttpMessageConverters类:

import org.springframework.boot.autoconfigure.web.HttpMessageConverters;

import org.springframework.context.annotation.*;

import org.springframework.http.converter.*;

@Configuration

public class MyConfiguration {

@Bean

public HttpMessageConverters customConverters() {

HttpMessageConverter<?> additional = ...

HttpMessageConverter<?> another = ...

return new HttpMessageConverters(additional, another);

}

}

任何在上下文中出现的HttpMessageConverter bean将会添加到converters列表,你可以通过这种方式覆盖默认的转换器

(converters)。

26.1.2.

2,

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})禁用自定义配置,排除相应主类即可

静态内容:

webappz整个标准只会在打成war时起作用,如果要打成jar包这个是不起作用的,springboot会从classpath下的/static(/public,/resources或/META-INF/resources)的文件

或servletcontext根目录提供静态内容

当你使用这些引擎的任何一种,并采用默认的配置,你的模板将会从src/main/resources/templates目录下自动加载。

目前的打成的jar包不含有webapp下的静态文件,怎么弄?????????????????????????????????????

3,@EnableWebSecurity通过标签关闭默认的配置;重新配置新的配置

@EnableWebSecurity bean来彻底关掉Spring Boot的默认配置。为了对它进行自定义,你需要使用

外部的属性配置和WebSecurityConfigurerAdapter类型的beans(比如,添加基于表单的登陆)

静态注入配置文件到bean的属性:

1,@Value

2,@ConfigurationProperties(prefix="connection") 所有前缀是connection都放在bean的同名属性中

@Component

@ConfigurationProperties(prefix="connection")

public class ConnectionSettings {

private String username;

private InetAddress remoteAddress;

// ... getters and setters

}

在其他类引用:

@Autowired

private ConnectionSettings connection;

通过@EnableConfigurationProperties注入

@Configuration

@EnableConfigurationProperties(ConnectionSettings.class)

public class MyConfiguration {

}

可以设置内嵌的servlet容器,不同容器对jsp的支持受限

Spring Data提供一个额外的功能,直接从接口创建Repository实现,

spring data jpa 是生成实体

传统上,JPA实体类被定义到一个persistence.xml文件中。在Spring Boot中,这个文件不是必需的,并被'实体扫描'替代。默

认情况下,在你主(main)配置类(被@EnableAutoConfiguration或@SpringBootApplication注解的类)下的所有包都将被

查找。(@EnableAutoConfiguration扫描主类所在包及所有子包)

配置文件的使用:

把配置文件中的属性值映射到bean中

1,通过前缀,和bean中对应名称的属性利用get,set自动将配置文件中的同名属性注入,后面直接通过get,set获取(类型安全的配置属性)可以松散的绑定

@Component

@ConfigurationProperties(prefix="connection")

public class ConnectionSettings {

private String username;

private InetAddress remoteAddress;

// ... getters and setters

}

# application.yml

connection:

username: admin

remoteAddress: 192.168.1.1

# additional configuration as required

松散的绑定

@Component

@ConfigurationProperties(prefix="person")

public class ConnectionSettings {

private String firstName;

}

person.firstName 标准驼峰规则

person.first-name 虚线表示,推荐用于.properties和.yml文件中

PERSON_FIRST_NAME 大写形式,使用系统环境变量时推荐

2,直接指定一个属性文件源,bean不需要属性名,后续通过操作这个bean来操作属性文件 (第三方配置)

@Configuration

@ConfigurationProperties

@PropertySource("classpath:paprocesser.properties") //只适用.properties,yml不行

public class ProcesserProperty extends Properties{

}

//或

@ConfigurationProperties(prefix = "foo")

@Bean

public FooComponent fooComponent() {

...

}

paprocesser.propertie

1310=inMoneyProcesser

//获取

String processerBeanName = processerProperty.getProperty("1310");

3,直接用@Value("${pa.url}")拿

@Value("${pa.url}")

private String paUrl ;

自动装配也就意味者会实例化自动配置中需要的bean

这些bean在用的时候可以通过set注入,也可以通过构造方法注入

你可以注入一个自动配置的 org.springframework.data.mongodb.MongoDbFactory 来访问Mongo数据库。

public class MyBean {

private final MongoDbFactory mongo;

@Autowired//构造方法注入

public MyBean(MongoDbFactory mongo) {

this.mongo = mongo;

}

自动装配的触发:

如果发现ActiveMQ在classpath下可用,Spring Boot会配置一个ConnectionFactory。如果需要代理,将会开启一个内嵌的,

已经自动配置好的代理(只要配置中没有指定代理URL)。

jmx相当于jconsle

在spring需要哪些bean被监控管理,只需要在此类上加注解即可,框架扫面到这些注解即会自动导出被监控的bean(springboot只要导入了jmx的包即集成好了jmx直接用即可)

,普通的spring中需要配置下jmx    @ManagedResource,@ManagedAttribute,@ManagedOperation)

测试:

使用注解的测试类(依赖注入,可以直接使用spring容器中的bean,否则拿不到上下文)

1,通过application运行的

@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class)

public class CityRepositoryIntegrationTests {

@Autowired

CityRepository repository;

// ...

}

2,以web方式运行的,通过http请求验证的(在一的基础上加@WebIntegrationTest即可)

@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class)

@WebIntegrationTest

public class CityRepositoryIntegrationTests {

@Autowired

CityRepository repository;

RestTemplate restTemplate = new TestRestTemplate();

// ... interact with the running server

}

server.context-path=/settlement

RestTemplate其实就是一个封装了原始的httpclient等基于地址的请求客户端

新的模块的引入:(一个包)

1,**config.java//相当于框架的配置文件,准备配置类

@Configuration

public class PaConfig {

@Bean

public RestTemplate restTemplate(){

RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();

RestTemplate paTemplate = restTemplateBuilder.build();

paTemplate.getMessageConverters().clear();

paTemplate.getMessageConverters().add(new PaHttpMessageConverter());

return paTemplate;

}

}

2,准备1中需要配置的类

3,使用类

thymeleaf模版

除了一般的springmvc自己的视图解析器功能,还有动静自动切换的功能

http://www.open-open.com/lib/view/open1451625468230.html

模版封装后使用思想:

<!-- Scans the classpath of this application for @Components to deploy as beans -->

       <context:component-scan base-package="com.test.thymeleaf.controller" />

       <!-- Configures the @Controller programming model -->

       <mvc:annotation-driven />

        <!--Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->

        <!--springMVC+jsp的跳转页面配置-->

       <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->

              <!--<property name="prefix" value="/WEB-INF/views/" />-->

              <!--<property name="suffix" value=".jsp" />-->

       <!--</bean>-->

       <!--springMVC+thymeleaf的跳转页面配置-->

       <bean id="templateResolver"          class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">

         <property name="prefix" value="/WEB-INF/views/" />

         <property name="suffix" value=".html" />

         <property name="templateMode" value="HTML5" />

       </bean>

       <bean id="templateEngine"           class="org.thymeleaf.spring4.SpringTemplateEngine">

          <property name="templateResolver" ref="templateResolver" />

       </bean>

       <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">//////spring提供自动封装的类thymeleaf-spring4-2.1.4.RELEASE.jar

         <property name="templateEngine" ref="templateEngine" />

       </bean>

thymeleaf-2.1.4.RELEASE.jar整个模版框架

thymeleaf-spring4-2.1.4.RELEASE.jar//spring提供自动封装的类

//一份静态的属性一份动态的属性

<img src="../../static/assets/images/qr-code.jpg" th:src="@{${path}}" alt="二维码" />

<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>

<input type="text" name="userName" value="James Carrot" th:value="${user.name}" />

--简单数据转换(数字,日期)

   <dt>价格</dt>

    <dd th:text="${#numbers.formatDecimal(product.price, 1, 2)}">180</dd>

   <dt>进货日期</dt>

   <dd th:text="${#dates.format(product.availableFrom, 'yyyy-MM-dd')}">2014-12-01</dd>

--字符串拼接

<dd th:text="${'$'+product.price}">235</dd>

猜你喜欢

转载自yuhuiblog6338999322098842.iteye.com/blog/2361445
今日推荐