springboot-web支持

本文探讨了SpringBoot中配置文件的加载与使用方法,包括自定义配置文件的引入及属性验证。介绍了如何通过过滤器实现请求处理的增强,并详细解释了bean属性验证的有效注解及其应用。此外,还讲解了两种成员变量的注入方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1)关于配置文件
可以在resource文件夹下面生成除了application.propertites之外的其他配置文件。
比如other.properties.

但是other.properties文件默认不会加载,所以在java的bean文件想引用该配置文件里面的属性,必须加注解@PropertySource(“classpath:other.properties”)

@PropertySource正常会配合如下两个注解使用:
@Component:代表这是一个普通的bean
@ConfigurationProperties(prefix=“other”):配置文件内容的前缀

如果想使用application.properties里面的属性,可以不需要指定@PropertySource,直接使用@Component和@ConfigurationProperties即可。

2)使用过滤器
web开发中,使用过滤器,我们正常会定义一个类实现Filter接口,然后在web.xml中将定义的过滤器配置起来。

springboot中同样需要定义一个类实现Filter接口,然后将该过滤器注册到上下文环境中,注册的方法是自定义一个过滤器注册Bean,FilterRegistrationBean,该bean负责对Filter的注册。

@Configuration
public class MyFilterConfiguration {
    @Bean
    public FilterRegistrationBean filterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFilter());
        registration.addUrlPatterns("/*");
        registration.setName("MyFilter");
        registration.setOrder(1);
        return registration;
    }
}

3)关于bean属性验证有效的几个注解
@NotEmpty(message=“不能为空”)
@Max(value = 100, message = “不大于120岁”)
@Min(value= 18 ,message= “必须不小于18岁!” )
@Length(min=6,message=“长度不小于6位”)

如果定一个bean(User)使用以上注解限制属性,配合如下使用方式:
@Valid @RequestBody User user,BindingResult result
从前段接受传参,会将验证的结果放置在BindingResult类型的result上。
可以按如下形式获取传参验证结果:

        System.out.println("user:"+user);
        if(result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                System.out.println(error.getCode()+ "-" + error.getDefaultMessage());
            }
        }

4)两个注解,用于注入成员变量:

    @Value("${book.title}")
    private String title;
    
    @Resource
    private Book book;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值