随笔记

平凡人平凡路,沉下心迈出步

0%

Spring一些小Tips

Bean的申明方式

  • 在A中实现FactoryBean接口来完成B的初始化,达到Bean的声明效果

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40

    public class TestA implements InitializingBean, FactoryBean<TestB> {
    @Getter
    @Setter
    private int a;
    private TestB testB;

    @Override
    public void afterPropertiesSet() throws Exception {
    this.testB = new TestB();
    }

    @Override
    public TestB getObject() throws Exception {
    return this.testB;
    }

    @Override
    public Class<?> getObjectType() {
    return (this.testB != null ? this.testB.getClass() : TestB.class);
    }

    @Override
    public boolean isSingleton() {
    return true;
    }
    }

    @Data
    public class TestB {
    private int b;
    }

    @Configuration
    public class BeanConfig {
    @Bean
    public TestA testA() {
    return new TestA();//此时B已经声明好了
    }
    }
  • 如何使用@Value初始化类静态属性

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @Component
    public class TestC {
    public static String s;

    @Value("${test.s}")
    public void setS(String sVal) {//使用set方法注入,方法需要是非静态的
    s = sVal;
    }

    public static String getS() {
    return s;
    }
    }
  • properties乱码解决

    乱码配置