Java开发的小技巧

本文汇总了SpringBoot开发中的实用技巧,包括启动时排除特定配置、JSON与对象转换、反射获取父类属性、Bean属性复制、项目启动时执行方法、普通项目转SpringBoot、main方法加载配置文件、@Conditional注解使用、YAML配置排除类等内容,帮助开发者提高工作效率。

整理开发中的小技巧,每个都不难,但总忍不住忘记,虽然自己写代码也能实现,但有现成的工具,为什么不用呢?

 

启动项目时,去掉不想注入的配置文件

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,DruidDataSourceAutoConfigure.class})

 

JSON和对象之间的转换

package com.alibaba.fastjson;
// java对象 转 json字符串
String s1 = JSON.toJSONString(user);
// json字符串 转 json对象
SONObject jsonObject = JSONObject.parseObject(s1);
// json字符串 转 java对象
User user1 = JSON.parseObject(s1, User.class);
// json字符串 转 list对象
List<User> users = JSONArray.parseArray(s1, User.class);
// list对象 转 json字符串
Object toJSON = JSON.toJSON(list);
// json字符串 转 Map
Map json = (Map) JSONObject.parse(str);
Map jsonMap = (Map) JSONObject.parseObject(str);
import net.sf.json.JSONObject;

//java对象 转 json对象
JSONObject json = JSONObject.fromObject(obj);
//java对象 转 json数组
JSONArray array = JSONArray.fromObject(stu);
//json对象 转 字符串 
String str = json.toString()
//json字符串 转 json对象
JSONObject jsonObject=JSONObject.fromObject(objectStr);
//json对象 转 java对象
Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
//json数组字符串 转 json数组
JSONArray jsonArray=JSONArray.fromObject(arrayStr);
//java数组 转 json数组
JSONArray listArray=JSONArray.fromObject(lists);
//json数组 转 java数组
List<Student> list2=(List<Student>)JSONArray.toList(JSONArray.fromObject(arrayStr), Student.class);
Student[] ss =(Student[])JSONArray.toArray(JSONArray.fromObject(arrayStr),Student.class);
//map 转 json对象
JSONObject mapObject=JSONObject.fromObject(map);
//map 转 json数组
JSONArray mapArray=JSONArray.fromObject(map);
//json字符串 转 map
JSONObject jsonObject=JSONObject.fromObject(strObject);
MyBean my=(MyBean)JSONObject.toBean(jsonObject, MyBean.class, map);

 

反射获得父类属性

private static String[] types = { "java.lang.Integer", "java.lang.Double", "java.lang.Float", "java.lang.Long",
            "java.lang.Short", "java.lang.Byte", "java.lang.Boolean", "java.lang.Char", "java.lang.String", "int",
            "double", "long", "short", "byte", "boolean", "char", "float" };

    private static Gson gson = new GsonBuilder().serializeNulls().create();

    /**
     * 获取方法参数名及对应值
     */
    public static String bulidParams(JoinPoint joinPoint, int size) throws Exception {
        String[] paramNames = getParamNames(joinPoint);
        Object[] args = joinPoint.getArgs();

        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (int k = 0; k < args.length; k++) {
            boolean clazzFlag = true;
            Object arg = args[k];
            if (arg == null) {
                continue;
            }
            if(paramNames[k].equals("idCard")||paramNames[k].equals("User_ID")){
                sb.append("\"sfzh\"");
            }else{
                sb.append("\""+paramNames[k]+"\"");
            }
            String typeName = arg.getClass().getTypeName();
            for (String type : types) {
                if (type.equals(typeName)) {
                    clazzFlag = false;
                    sb.append(":\"").append(argValue(arg)).append("\",");
                }
            }
            if (clazzFlag)
                sb.append(":{").append(getFieldsValue(arg)).append("},");
            if (sb.toString().length() >  size-1) break;
        }
        sb.append("}");
        return sb.toString();
    }

 private static String[] getParamNames(JoinPoint joinPoint) {
        return ((MethodSignature) joinPoint.getSignature()).getParameterNames();
    }

    private static String argValue(Object arg) {
        String argStr = gson.toJson(arg);
        return argStr.length() > 256 ? argStr.subSequence(0, 256) + "..." : argStr;
    }


    /**
     * 获取对象中的参数名及对应参数值
     */
    private static String getFieldsValue(Object obj) throws Exception {
        Field[] fields = getAllFields(obj);//obj.getClass().getDeclaredFields();
        StringBuilder sb = new StringBuilder();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                field.get(null);// 只能获取静态常量
            } catch (NullPointerException e) {
                Object objArg = field.get(obj);
                if (objArg == null) {
                    continue;
                }
                for (String type : types) {
                    if (field.getType().getName().equals(type)) {
                        sb.append("\"").append(field.getName()).append("\"").append(":").append(argValue(objArg)).append(",");
                    }
                }
            }
        }
        return sb.toString();
    }

    //获得父类对象的参数
    public static Field[] getAllFields(Object object){
        Class clazz = object.getClass();
        List<Field> fieldList = new ArrayList<Field>();
        while (clazz != null){
            fieldList.addAll(new ArrayList<Field>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }

 

BeanUtils.copyProperties(t,stu);


import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;

public class Demo {
    public static void main(String[] args) {
        Teacher t = new Teacher();
        t.setName("mary");
        t.setSex("女");
        Student stu = new Student();
        BeanUtils.copyProperties(t,stu); //student 和 teacher 字段相同
        System.out.println("teacher 和 student copy 结果: "+JSON.toJSON(stu).toString());

        Student1 stu1 = new Student1();
        BeanUtils.copyProperties(t,stu1);//student 和 teacher 字段相同,但有字段在父类中
        System.out.println("teacher 和 student1 copy 结果: "+JSON.toJSON(stu1).toString());

        Student2 stu2 = new Student2();//student 比 teacher 少一个字段
        BeanUtils.copyProperties(t,stu2);
        System.out.println("teacher 和 student2 copy 结果: "+JSON.toJSON(stu2).toString());

        Student3 stu3 = new Student3();//student 比 teacher 少一个对应字段,多一个其他字段
        BeanUtils.copyProperties(t,stu3);
        System.out.println("teacher 和 student3 copy 结果: "+JSON.toJSON(stu3).toString());
    }
}

class Student3 implements Serializable{
    private String sex;
    private String age;
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}
class Student2 implements Serializable{
    private String sex;
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
}
class Student1 extends Person implements Serializable{
    private String sex;
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
}
class Student implements Serializable{
    private String name;
    private String sex;
    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;
    }
}

class Person implements Serializable {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

class Teacher implements Serializable {
    private String name;
    private String sex;
    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;
    }
}

 

项目启动时执行的方法:

@Component
public class AppRunningImp implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
       ...
    }
}

 

普通项目转spring:

pom.xml 文件:
     <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

启动类加上注解 和启动SpringApplication入口方法
@SpringBootApplication
public class ProducerApplication {

    public static void main(String[] args) throws IOException {
        SpringApplication.run(ProducerApplication.class);
    }
}

 

main方法中加载配置文件

    private void duli() throws IOException {
        String[] xml = new String[] {"producer.xml"};
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(xml);
        context.start();
        System.in.read();//按任意键退出
    }

 

@Conditional注解 以及相关@ConditionalXXXX注解

注解相关使用可以搜索网上资料。用途是啥呢?即使加了@Configuration ,@Service等注解,也可以选择是否生成bean!

使用场景:例如引用redis包,但配置redis信息才生成redis相关配置文件的bean,不配置则不生成,启动不报错。

 

 

yml 中去除 配置类

spring:
  autoconfigure.exclude: org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure

Spring Boot 通用配置参数
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

Spring 下所有项目的文档, Spring boot 只是其中一个项目
https://spring.io/docs/reference

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值