springboot项目抓数据后优化配置及四个补充

时间:2024-01-21 21:23:09

  昨天搞了一个抓取某某平台信息的抓取功能,其中有一个地址url,昨天是写死的,之前也进行配置过,印象有些模糊,今天想配置一下,在properties文件中,由此引发了下面的一系列总结操作:

  1、原始模式,引用加载模式

    我所说的这种方式是通过直接代码引用文件方式,如下:

//引入的相关类
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
//properties_file为 src/main/resource下的路径 比如 configuration/application.properties
PropertiesConfiguration conf = new PropertiesConfiguration(properties_file_name);
//这步我认为是很有意义的
//配置文件修改后自动重新加载
Configuration configuration = conf.setReloadingStrategy(new FileChangedReloadingStrategy());
//然后通过 configuration 的相关方法就可以获取到key对应的value
String value = configuration.getString("key") 

  2、springboot项目自动加载模式

  springboot项目加载的默认配置文件是在  src/main/resource 目录下的application.properties文件信息,可以再该文件中进行配置,例如:

  springboot项目抓数据后优化配置及四个补充

  然后在所写的组件类中

            @Autowired
private Environment environment;
  //使用该方法就可回去属性文件中的对应的name value值
environment.getProperty("name");

  3、springboot项目手动加载模式

   这种方式可以有多种方式进行加载,这里进行介绍,单key加载和多key加载

   单key加载:通过对单个key对应的value值逐一加载

//这里是自己所定义的属性文件key:value信息
person.name=yijianlian
person.sex =man @Component
@PropertySource("classpath:application.properties")
public class PropertiesConfig { @Value("${person.name}")
public String name; @Value("${person.sex}")
public String sex ; //getter setter .. //constructor .. }

多key加载: 多key一次性加载 如下


//这里是自己所定义的属性文件key:value信息
person.name=yijianlian
person.sex =man
@Component
@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix = "person") //绑定配置文件的值
public class PropertiesConfig { public String name; public String sex ; public PropertiesConfig() {
super();
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
}
}

补充一、yaml用法:

  以空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的,大小写敏感

k:(空格)v:

#空格不能省
#k: v:字面直接来写;
# 字符串默认不用加上单引号或者双引号;
# "":双引号;不会转义字符串里面的特殊字符;特殊字符会作为本身想表示的意思
# name: "zhangsan \n lisi":输出;zhangsan 换行 lisi
# '':单引号;会转义特殊字符,特殊字符最终只是一个普通的字符串数据
# name: ‘zhangsan \n lisi’:输出;zhangsan \n lisi
表示对象、Map(属性和值)(键值对)语法:
k: v:在下一行来写对象的属性和值的关系;注意缩进,对象还是k: v的方式
friends:
lastName: zhangsan
age: 20
行内写法:
friends: {lastName: zhangsan,age: 18}
表示数组的语法
用- 值表示数组中的一个元素(- 和属性之间空格不能省)
pets:#(数组名)
- cat#(属性)
- dog#(属性)
- pig#(属性)
行内写法
pets: [cat,dog,pig]

如:

package com.byls.springbootdemo.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中
* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
* prefix = "person":配置文件中哪个下面的所有属性进行一一映射
*
* 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
*
*/
@Component//将Person类注册到容器中
@ConfigurationProperties(prefix = "person") //绑定配置文件的值
public class Person {
private String lastName;//名字
private Integer age;//年龄
private Boolean boss;//是否是老板
private Date bir;//生日 private Map<String,Object> maps;//map集合
private List<Object> lists;//list集合
private Dog dog;//Dog类对象 只有name 和 age属性 public Person() {
} @Override
public String toString() {
return "Person{" +
"lastName='" + lastName + '\'' +
", age=" + age +
", boss=" + boss +
", bir=" + bir +
", maps=" + maps +
", lists=" + lists +
", dog=" + dog +
'}';
} public Person(String lastName, Integer age, Boolean boss, Date bir, Map<String, Object> maps, List<Object> lists, Dog dog) {
this.lastName = lastName;
this.age = age;
this.boss = boss;
this.bir = bir;
this.maps = maps;
this.lists = lists;
this.dog = dog;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public void setAge(Integer age) {
this.age = age;
} public void setBoss(Boolean boss) {
this.boss = boss;
} public void setBir(Date bir) {
this.bir = bir;
} public void setMaps(Map<String, Object> maps) {
this.maps = maps;
} public void setLists(List<Object> lists) {
this.lists = lists;
} public void setDog(Dog dog) {
this.dog = dog;
} public String getLastName() {
return lastName;
} public Integer getAge() {
return age;
} public Boolean getBoss() {
return boss;
} public Date getBir() {
return bir;
} public Map<String, Object> getMaps() {
return maps;
} public List<Object> getLists() {
return lists;
} public Dog getDog() {
return dog;
}
}

对应的yaml文件为: 

person:
name: byls
age: 22
boss: true
bir: 2017/12/01
maps: {k1: v1,k2: v2}
lists:
- zs
- ls
dog:
name: baibai
age: 10

补充二:@ConfigurationProperties 和@Value 区别

             前者是 批量注入配置文件中的属性,后者是单个注入,同时后者在业务逻辑中需要获取某个属性值时使用。

      相同点,若没有指定特定文件时如:@PropertySource("classpath:application.properties") ,两者指定的公有文件都是默认配置文件application.properties或者application.yml

     例如:

package com.byls.springbootdemo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; /**
* @Value的一个简单的使用场景例子
*/
@RestController //@ResponseBody和@Controller的结合
public class HelloController {
@Value("${person.name}")//使用@Value从配置文件中取单个值
private String name; @RequestMapping("/hello")//设置请求路径
public String hello(){
return "hello"+name;
}
}

补充三:springboot 中创建组件两种方式:

    方式一:

    @ImportResource 注解方式:

    创建一个hello.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--向spring容器中添加helloService组件-->
<bean id="helloService" class="com.test.HelloService"></bean>
</beans>

    然后在主函数中注解加入:

/**
* springboot主程序入口类
*/
@ImportResource(locations = {"classpath:hello.xml"})//依赖注入方式
@SpringBootApplication
public class SpringbootApplication { public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
} }

进行测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootDemoApplicationTests { @Autowired
private ApplicationContext applicationIoc; //spring容器对象 @Test
public void testHelloService(){
//判断容器中是否包含某个bean 包含为true 反之为false
boolean flag = applicationIoc.containsBean("helloService"); } }

   方式二:配置注入@Configuration和@Bean组合

  

/**
* 配置类
*/
@Configuration//指定这是一个配置类,用于替代之前的配置文件
public class HelloConfigution { //将方法的返回值添加到容器中,容器中组件的id就是方法的返回值
@Bean
public HelloService helloService(){
return new HelloService();
}
}

补充四:@Controller 和@RestController 区别

  @RestController注解相当于@ResponseBody + @Controller合在一起的作用

  如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,

       配置的视图解析器InternalResourceViewResolver则不起作用,返回的内容就是Return 里的内容(String/JSON)

如果使用@RestController注解Controller,需要返回到指定页面,

则需要配置视图解析器InternalResourceViewResolver,可以利用ModelAndView返回试图

  如果使用@Controller注解Controller,如果需要返回JSON,XML或自定义mediaType内容到页面

    则需要在对应的方法上加上@ResponseBody注解,以下两种方式均可

  springboot项目抓数据后优化配置及四个补充

  springboot项目抓数据后优化配置及四个补充