(一)属性注入方式

当前SpringBoot中的属性注入方式常见的有以下三种,如下所示:

方式一:继承Spring原有的属性注入方式

   使用方式是通过@Component+@Value,Demo如下:

/**
 * 第一种属性注入方式:通过Component+@Value
 * */
@Component
@Data
public class Info {

    @Value("${student.name}")
    private String name;

    @Value("${student.age}")
    private Integer age;
}


其中,application.properities中的文件内容如下:

student.name=huaiheng
student.age=18

方式二:类型安全的属性注入方式

   这种方式实际上可看作是方式一的一种简化,通过使用@ConfigurationProperities+Set方式完成注入,但是需要在启动类上需要显示将该类的实例注册到IOC容器中,Demo如下:

/**
 * 配置类,其中属性名应与application.properities中的配置属性名保持一致
 * */
@ConfigurationProperties(prefix = "student")
@Data
public class Info2 {
    private String name;
    private String age;
}

/**
* 启动类,指明将info2的实例注册到IOC中
*/
@EnableConfigurationProperties(Info2.class)
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

/**
* application.properities
*/
student.name=huaiheng
student.age=18

方式三:使用构造器注入方式

有时我们需要在一个组件中引入另一个组件功能,这时bean的引入除了使用@Autowired方式外还可以使用构造器注入方式,Demo如下所示:

/***
* 常见方式
*/
@Component public class Info3 {
@Autowired private Info2 info2; public String getName(){ return info2.getName(); } public String getAge(){ return info2.getAge(); } }


/***
* 构造器方式
*/
@Component
public class Info3 { private Info2 info2; public Info3(Info2 info2) { this.info2 = info2; } public String getName(){ return info2.getName(); } public String getAge(){ return info2.getAge(); } }

猜你喜欢

转载自www.cnblogs.com/huaiheng/p/12825583.html
今日推荐