Spring boot 注解 + java 技巧一

项目:WECHAT(6.8-8.2)

    【一】、注解

        [参考]:https://www.cnblogs.com/tanwei81/p/6814022.html

        ①@Valid

public ResultVO<Map<String, String>> creat(@Valid OrderForm orderForm,BindingResult bindingResult){
    if (bindingResult.hasErrors()) {
	log.error("参数不正确");
	bindingResult.getFieldError().getDefaultMessage());
    }
}

         @Valid注解用于校验,需要在实体类(Bean)的相应字段上添加用于充当校验条件的注解:例如:@Min,如下代码(age属于OrderForm类中的属性).其次在controller层的方法的要校验的参数上添加@Valid注解,可以传入BindingResult对象,用于获取校验失败情况下的反馈信息,使用可以参考:http://blog.csdn.net/xzmeasy/article/details/76098188

public class OrderForm{
    @Max(value = 100,message="最大年龄不得大于100")
    @Min(value = 18, message="最小年龄不得小于18")	
    private Integer age;
}

        ②@RequestParam

        @RequestParam注解主要有哪些参数:
                value:参数名字,即入参的请求参数名字,如username表示请求的参数区中的名字为username的参数的值将传入;
                  required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报404错误码;

            defaultValue:默认值,表示如果请求中没有同名参数时的默认值,默认值可以是SpEL表达式,如“#{systemProperties['java.vm.version']}”。

public String requestparam5(  
@RequestParam(value="username", required=true, defaultValue="zhang") String username) {}

        ③@Autowired  自动导入

        ④@RestController 

        @RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器bean,并且是将函数的返回值以json形式传入http请求中,他和@Controller注解不同,@Controller注解传入的是一个视图

        ⑤@PathVariable

        @RequestMapping(value ="find/{id}/{name}")
	public User get(@PathVariable int id,@PathVariable String name){
		User u = new User();
		u.setId(id);
		u.setName(name);
		return u;
	}

        @PathVariable获取,请求路径中的动态参数作为值,比如find/{id}/{name},其中用{  }包含的就是动态参数,此外他们的名字应该对应:如下路径里{id},应该对应@PathVariable(“id”)的id

        @GetMapping(value = "deleteById/{id}")
	public String deleteById(@PathVariable("id") Integer stu_id){
		studentReposity.delete(stu_id);
		return "delete success";
	}

        ⑥配置注解@ConfigurationProperties,@Component

        核心配置文件application.properties内容如下:

test.msg=Hello World Springboot!
  • 方法一、使用@Value方式(常用):
@RestController
public class WebController {

    @Value("${test.msg}")
    private String msg;

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index() {
        return "The Way 1 : " +msg;
    }
}

注意:@Value的${}中包含的是核心配置文件中的键名。

  • 方法二、使用Environment方式
@RestController
public class WebController {

    @Autowired
    private Environment env;

    @RequestMapping(value = "index2", method = RequestMethod.GET)
    public String index2() {

        return "The Way 2 : " + env.getProperty("test.msg");
    }
}

注意:这种方式是依赖注入Evnironment来完成,在创建的成员变量private Environment env上加上@Autowired注解即可完成依赖注入,然后使用env.getProperty("键名")即可读取出对应的值。


@ConfigurationProperties(locations = "classpath:config/my-web.properties", prefix = "web")


使用自定义配置文件

有时候我们不希望把所有配置都放在application.properties里面,这时候我们可以另外定义一个,这里我明取名为test.properties,路径跟也放在src/main/resources下面。

test.msg="hello"
test.time="2018"

我们新建一个bean类,如下:

@ConfigurationProperties(prefix = "test")
@PropertySource("classpath:test.properties")
@Component
public class MyWebConfig {

    private String msg;

    private String time;

    //这里省略了set,get方法
}

这里要注意哦,有一个问题,如果你使用的是1.5以前的版本,那么可以通过locations指定properties文件的位置,这样:

@ConfigurationProperties(locations = "classpath:config/test.properties", prefix = "test")

注意:

  • @ConfigurationProperties注释中有两个属性:

    • locations:指定配置文件的所在位置
    • prefix:指定配置文件中键名称的前缀(我这里配置文件中所有键名都是以web.开头)
  • 使用@Component是让该类能够在其他地方被依赖使用,即使用@Autowired注释来创建实例。

随机值配置

配置文件中${random} 可以用来生成各种不同类型的随机值,从而简化了代码生成的麻烦,例如 生成 int 值、long 值或者 string 字符串。


参考地址:https://www.cnblogs.com/zheting/p/6707036.html

                http://blog.csdn.net/zsl129/article/details/52880798


        ⑦@Bean注解

        @Bean是一个方法级别上的注解,主要用在@Configuration注解的类里也可以用在@Component注解的类里。添加的bean的id为方法名,他的主要作用类似与xml里配置,作用为:注册bean对象

@Configuration
public class AppConfig {
    
//@Bean注解注册bean,同时可以指定初始化和销毁方法    
//@Bean(name="testNean",initMethod="start",destroyMethod="cleanUp")
   @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }

}
 
(1)、@Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同; 

(2)、@Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域; 

(3)、既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Ripository等注解注册bean,当然需要配置@ComponentScan注解进行自动扫描。


这个配置就等同于之前在xml里的配置

<beans>
    <bean id="transferService" class="com.acme.TransferServiceImpl"/>
</beans>

参考资料:http://blog.csdn.net/javaloveiphone/article/details/52182899



    【二】、CollectionUtils、StringUtils类的使用

        ①判断集合是否为空CollectionUtils.isEmpty

        ②判断字符是否为空StringUtils.isEmpty


   【三】、对于返回前端参数进行限制

        ①如果返回前端参数,可以不用返回的,显示为null,可以添加注解

                方法一:在他的实体类Bean上添加注解——————针对单个类

//@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)//这个用法和下面一个功能,但是被废弃掉了
//@JsonInclude(JsonInclude.Include.NON_NULL)
public class Order {

}

                方法二:在配置文件中添加,统一处理,例如yml文件内——————针对全部

spring:
  jackson:
    default-property-inclusion: non-null

        ②对于必须返回的,可以配置初始化参数,显示为""

                方法一:在对应的Bean类里初始化,

List<OrderDetail> orderDetailList = new ArrayList<OrderDetail>();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值