springboot環境配置+使用

@SpringBootApplication內部分為三個注解

  • @EnableAutoConfiguration啟用Spring Boot的自動配置機制
  • @ComponentScan:對應用程序所在的軟件包啟用@Component掃描
  • @Configuration:允許在上下文中注冊額外的beans或導入其他配置類
  • @Bean向容器中添加實體bean,可以通過@Conditional來添加條件是否添加此bean
  • @Autowired(required = false)注入bean對象,如果沒有就會報錯,可以添加required=false來設置可以為空


Starters類路徑依賴項

Spring Boot提供了一些“Starters”,可讓您將jar添加到類路徑中。我們的示例應用程序已經在POM的parent部分使用了spring-boot-starter-parent。spring-boot-starter-parent是一個特殊的啟動器,提供有用的Maven默認值。它還提供了一個 dependency-management 部分,以便您可以省略version標簽中的“祝福”依賴項。


springboot啟動方式

 //方式一
    public static void main(String[] args) {
    //這個方法里面首先要創建一個SpringApplication對象實例,然后調用這個創建好的SpringApplication的實例方法
        SpringApplication.run(Application.class, args);
    }
    //方式二
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MySpringConfiguration.class);
        app.run(args);
    }
    //方式三
    public static void main(String[] args) {
        new SpringApplicationBuilder()
            .sources(Parent.class)
            .child(Application.class)
            .run(args);
    }

SpringApplicationBuilder:鏈式調用,常見的用例是設置活動配置文件和默認屬性以設置應用程序的環境:


外部資源配置

  • 啟動程序上面添加
//添加注解
@PropertySource(value= "classpath:properties/config.properties",encoding = "UTF-8",ignoreResourceNotFound = true)

//獲取屬性
@Component
public class MyBean {

    @Value("${name}")
    private String name;

    // ...

}



多個環境配置yml文件

//pom文件配置
<profiles>
        <profile>
            <!-- 開發環境 -->
            <id>dev</id>
            <properties>
                <profiles.active>dev</profiles.active>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <!-- 測試環境 -->
            <id>test</id>
            <properties>
                <profiles.active>test</profiles.active>
            </properties>
        </profile>
        <profile>
            <!-- 生產環境 -->
            <id>pro</id>
            <properties>
                <profiles.active>pro</profiles.active>
            </properties>
        </profile>
    </profiles>  
//環境文件夾要設置為resources類型

加載Yaml文件

  • YamlPropertiesFactoryBean將YML加載為properties
  • YamlMapFactoryBean將Yml加載為Map
  • spring.profiles.active添加加載的配置,可以通過這個設置不同環境加載不同的配置
application-dev.yml
application-pro.yml
srping.profiles.active=dev;
  • YAML列表表示為具有[index]解除引用的屬性鍵
my:
servers:
    - dev.example.com
    - another.example.com
//轉換為
my.servers[0]=dev.example.com
my.servers[1]=another.example.com
  • 綁定前面yml中的屬性,也可用@Value綁定其中的屬性
@ConfigurationProperties(prefix="my")
public class Config {

    private List<String> servers = new ArrayList<String>();

    public List<String> getServers() {
        return this.servers;
    }
}
  • 在單一文件中,可用連續三個連字號(---)區分多個文件另外,還有選擇的連續三個點號(...)用來表示文件結尾.
    ==Ymal缺點:無法使用@PropertySource注釋加載YAML文件。因此,如果您需要以這種方式加載值,則需要使用屬性文件。==

<font color="red"> @ConfigurationProperties與@Value:@Value不支持寬松綁定, @ConfigurationProperties支持多屬性pojo綁定</font>


整合logback

添加logback.xml

 <!--設置存儲路徑變量,./代表相對路徑,項目根目錄-->
    <property name="LOG_HOME" value="./clientA/log"/>

==只需要改動文件地址,不用導依賴,改配置==


JSON

spring Boot提供三個JSON映射庫集成

  • Gson:可以快速的將一個 Json 字符轉成一個Java對象,或者將一個 Java 對象轉化為Json字符串
//默認不對空屬性序列化
private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
 /** 對屬性值為 null 的字段進行序列化*/
String personStrFinal = new GsonBuilder().serializeNulls().create().toJson(person);
  • Jackson
  • JSON-B
    ==對比:jackson效率更快,Gson功能更多可以做更多的操作,一般使用Gson==


HttpMessageConverter

  • 是用來處理request和response里的數據的。Spring內置了很多
  • AbstractHttpMessageConverter:可以針對某個類進行操作
    ==要求:
    第一個是pom文件中加入jackson的jar包,第二個是在配置文件中加入MappingJackson2HttpMessageConverter==

全局異常處理

@RestControllerAdvice
/*@ControllerAdvice(annotations = {PCInfoController .class}) 配置你需要攔截的控制器,
@ControllerAdvice(basePackages = "com.demo") 配置你需要路徑下的控制器*/
public class UserCheckExection {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object checkExectionHandler(HttpServletRequest request, MethodArgumentNotValidException exception) {
       List<FieldError> list = new ArrayList();
        FieldError error = (exception.getBindingResult().getFieldErrors()).get(0);
        HashMap<String,Object> map = new HashMap<>();
        map.put("msg",error.getDefaultMessage());
        map.put("code","12306");
        return map;
    }
}




嵌入式Servlet容器

  • tomcat(springboot-web-starter中已經嵌入tomcat)
  • Jetty(使用需要exclusion中排除tomcat)
  • Undertow



訪問靜態資源并不需要經過控制器

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //第一個參數是在訪問url中加的路徑,第二個參數是資源在目錄中的真實路徑
       registry.addResourceHandler("/**").addResourceLocations("classpath:/static1/")
       .addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/");
    }
}

==第二個參數格式"classpath:/html/"(代表resources下html目錄)也可寫成file:/html/這種是媒體資源,鏈式調用可以寫多個資源地址==
<font color="red">springboot默認的攔截器寫好了靜態資源訪問方式,因此在yml里面配置不管用,需要通過WebMvcConfigurer覆蓋他的攔截器</font>



配置訪問后綴符

//打開后綴匹配開關
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseRegisteredSuffixPatternMatch(true);
    }
//將后綴符匹配到url方法上
    @Bean
    public ServletRegistrationBean servletRegistrationBean(DispatcherServlet dispatcherServlet) {
        ServletRegistrationBean<DispatcherServlet> servletServletRegistrationBean = new ServletRegistrationBean<>(dispatcherServlet);
        servletServletRegistrationBean.addUrlMappings("*.do");
        servletServletRegistrationBean.addUrlMappings("*.html");
        servletServletRegistrationBean.addUrlMappings("*.png");
        servletServletRegistrationBean.addUrlMappings("*.jpg");
        return servletServletRegistrationBean;
    }



配置攔截器、過濾器、監聽器

<a >參考配置地址</a>

erueka服務關不掉,刪除依賴,注釋配置和注解都無效

==刪除maven倉庫里面的包==


項目啟動后自動運行的兩個類

  • CommandLineRunner
  • ApplicationRunner
  • ==區別:CommandLineRunner將啟動函數傳入的參數不封裝傳入run方法,ApplicationRunner封裝了參數在ApplicationArguments類中==
  • 共同點:可以重復創建,需要用線程執行內容,因為他們會影響主線程運行
  • 通過@Order(2)來標準順序
  • 參數類型String... 可填可不填,數組類型


Apache Solr搜索引擎

Elasticsearch搜索引擎



RabbitMQ是一個基于AMQP協議的輕量級,可靠,可擴展且可移植的消息代理

  • YML配置
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=secret



REST(包括get、post、delete等請求方式請求)

  • spring內置(REST相較于httpclient代碼更簡潔,效率待驗證)
//配置中加入restTemplate
@Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
//
public Object weather(@ApiParam(value = "語言") @RequestParam(value = "language") String language, @ApiParam(value = "地址") @RequestParam(value = "location") String location) throws URISyntaxException, IOException {
        URI uri = new URIBuilder()
                .setScheme("https").setHost("api.seniverse.com").setPath("/v3/weather/now.json")
                .setParameter("key", "w99tf57ghc86thhv")
                .setParameter("language", language)
                .setParameter("location", location)
                .build();
        return restTemplate.getForObject(uri, Object.class);



JavaMailSender

  • SimpleMailMessage(實例)
  • MimeMailMessage(實例)


JAVA 事務

  • JDBC事務(普通事務)
    1. 數據庫事務中的本地事務,通過connection對象控制管理,只支持一個庫不能多個庫
  • JTA事務
    1. JTA事務比JDBC更強大,支持分布式事務(當然也支持本地事務)包含jdbc、jms等java組件事務回滾
  • 容器管理事務:常見hibnate、spring等容器
  • 編程式事務:通過代碼對事務進行控制,粒度更小
  • 聲明式事務:xml或注解方式實現,實現建立在aop上,在方法開始前創建一個事務,在執行完目標方法之后檢查事務情況再進行提交或回滾
//value可不寫
@Transactional(value = "rabbitTxManage", rollbackFor = Exception.class)



Quartz Scheduler

  • JobDetail:定義一個特定的工作。可以使用JobBuilderAPI構建JobDetail個實例
  • Calendar
  • Trigger:定義何時觸發特定作業。
  • QuartzJobBean作業類


測試spring-boot-starter-test

  • JUnit:單元測試Java應用程序的事實標準。
  • Spring測試和Spring Boot測試:Spring Boot應用程序的實用程序和集成測試支持。
  • AssertJ:一個流暢的斷言庫。
  • Hamcrest:匹配器對象庫(也稱為約束或謂詞)。
  • Mockito:一個Java 模擬框架。
  • JSONassert:JSON的斷言庫。
  • JsonPath:JSON的XPath。
  • ==springboot項目單元測試默認會掃描所有類啟動程序,只需添加類就可以不啟動程序==

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = DemoApplicationTests.class)


?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容