springboot常用操作-持续更新中

@Value取值

application.yml如下

native:
  tem: D:\tem\
  clear-time: "13:31"

@Value 读取配置文件的属性值
注意:如果配置文件中没有设置@Value注入的值,在项目启动的时候找不到该值会报错

 /**
  * 定时任务时间
  */
@Value("${native.clear-time}")
private String clearTime;

@Value yml配置中取时间字符串值,需加上 “” 双引号

@Value设置默认值

通过 “:xxxx ” 来定义默认值
设置默认值可以减少配置文件需要配置的数据,更加简单化

  /**
  * 定时任务时间:默认值  12:00:00
  */
@Value("${native.clear-time:12:00:00}")
private String clearTime;

项目启动时进行初始化操作

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 项目启动时进行初始化操作
 */
@Component
@Order(1) //指定顺序
public class RunnerOne implements CommandLineRunner {

    @Override
    public void run(String... args) {
			System.out.println("项目启动时进行初始化操作");
    }

}

spring中Constructor、@Autowired、@PostConstruct的顺序


Constructor(构造方法) >> @Autowired >> @PostConstruct

要将对象p注入到对象a,那么首先就必须得生成对象a和对象p,才能执行注入。所以,如果一个类A中有个成员变量p被@Autowried注解,那么@Autowired注入是发生在A的构造方法执行完之后的。
如果想在生成对象时完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么久无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。

扩展使用SpringMVC

官方文档如下:
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.

我们要做的就是编写一个@Configuration注解类,并且类型要为WebMvcConfigurer,还不能标注@EnableWebMvc注解;我们去自己写一个;我们新建一个包叫config,写一个类MyMvcConfig;

//应为类型要求为WebMvcConfigurer,所以我们实现其接口
//可以使用自定义类扩展MVC的功能
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override public void addViewControllers(ViewControllerRegistry registry) {   
         //其中image表示访问的前缀。"file:F:/img/"是文件真实的存储路径
        registry.addResourceHandler("/image/**").addResourceLocations("file:F:/img/");
   }
}

@Configuration和@Bean bean注入spring容器

public class Person {

    private String name;
    
    private Integer age;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Integer getAge() {
        return age;
    }
 
    public void setAge(Integer age) {
        this.age = age;
    }
 
    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
 
    @Override
    public String toString() {
        return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
    }
}
@Configuration
public class BeanConfig {

    @Bean(name = "bean1")
    public Person person1(){
        return new Person("Bill Gates",62);
    }
 
    @Bean("bean2")
    public Person person2(){
        return new Person("Linus",48);
    }
}

@Conditional注解

此注解可以标注在类和方法上
传入一个Class数组,并且需要继承Condition接口
Condition是个接口,需要实现matches方法,返回true则注入bean,false则不注入。

因此SpringBoot基于@Condition接口,进一步封装了@ConditionalOnXXX注解。对于这些注解,开发者可以不用再实现Condition接口,而是直接在@ConditionalOnXXX注解的value值中,写入判断的条件(例如class名称、path路径、properties配置等),进一步减少了开发量。

@ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)
@ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean)
@ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean)
@ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean)
@ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean)
@ConditionalOnWebApplication (web应用生效)

日志打印

private static final Logger log = LoggerFactory.getLogger(GenerateQRCode.class);

spring boot项目单元测试时,@Autowired无法注入Service解决方式

首先确认:测试类所在包名要和启动类一致

@ConditionalOnProperty的作用和用法

在spring boot中有时候需要控制配置类是否生效,可以使用@ConditionalOnProperty注解来控制@Configuration是否生效.

@Configuration
@ConditionalOnProperty(prefix = "filter",name = "loginFilter",havingValue = "true")
public class FilterConfig {
	//prefix为配置文件中的前缀,
	//name为配置的名字
	//havingValue是与配置的值对比值,当两个值相同返回true,配置类生效.
    @Bean
    public FilterRegistrationBean getFilterRegistration() {
        FilterRegistrationBean filterRegistration  = new FilterRegistrationBean(new LoginFilter());
        filterRegistration.addUrlPatterns("/*");
        return filterRegistration;
    }
}

```yaml
filter:
	loginFilter: true

springboot读取resources文件夹下边的文件

第一种方法
File file =  ResourceUtils.getFile("classpath:template/科研项目模板.xlsx");
//获取文件的相对路径  可在控制台打印查看输出结果
String filePath = ResourceUtils.getFile("classpath:template/科研项目模板.xlsx").getPath();

第二种方法
//直接将目标文件读成inputstream  this指当前类的实例对象
InputStream ins = this.getClass().getClassLoader()
.getResourceAsStream("template/科研项目模板.xlsx");
File file = new File(ins);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用Spring Boot与MyBatis-Plus连接SQL Server时,可能会遇到以下问题: 1. 驱动问题:首先需要引入SQL Server的JDBC驱动,可以在pom.xml文件添加依赖。常用的驱动有`com.microsoft.sqlserver.jdbc.SQLServerDriver`和`net.sourceforge.jtds.jdbc.Driver`。确保驱动版本与SQL Server版本兼容。 2. 数据库连接配置:在application.properties或application.yml文件,需配置SQL Server的连接信息,包括数据库地址、端口、用户名、密码等。注意要正确配置驱动名称、连接URL以及字符集等。 3. 数据库版本兼容性:确保使用的SQL Server版本与MyBatis-Plus和JDBC驱动兼容。不同版本的SQL Server可能在SQL语法、特性或驱动接口上有所区别。 4. 数据库表映射:在使用MyBatis-Plus进行ORM映射时,需要在实体类使用注解配置数据表名、字段名和主键等信息。同时,要确认实体类和数据表的字段类型、长度、精度等匹配。 5. 数据库连接池配置:可以使用Spring Boot提供的连接池技术,如HikariCP或Tomcat连接池。根据并发需求和性能要求,配置合适的连接池大小、最大等待时间和最大空闲时间等参数。 6. 异常处理与日志记录:在连接SQL Server过程,可能会出现连接异常、语法错误等问题。需要适当处理这些异常,并进行日志记录以便排查和分析问题。 通过解决上述问题,我们可以成功连接SQL Server数据库,并使用MyBatis-Plus进行数据操作和ORM映射。持续的测试和调试可以保证系统的稳定性和性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值