SpringBoot 01: JavaConfig + @ImportResource + @PropertyResource( 二 )

  • @ComponentScan:SpringConfig类上
  • @Value:待注入值的属性上
  • 代码实现
    • SpringConfig类
    package com.example.springboot.configuration;import com.example.springboot.model.Student;import org.springframework.context.annotation.*;@PropertySource(value = "https://www.huyubaike.com/biancheng/classpath:food.properties")@ComponentScan(basePackages = "com.example.springboot.model")public class SpringConfig {}
    • food.properties
    food.name=饺子food.price=13
    • JiaoZi类
    package com.example.springboot.model;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Component("jiaozi")public class JiaoZi {@Value("${food.name}")private String name;@Value("${food.price}")private double price;@Overridepublic String toString() {return "JiaoZi{" +"name='" + name + '\'' +", price=" + price +'}';}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public JiaoZi(String name, double price) {this.name = name;this.price = price;}public JiaoZi() {}}测试代码package com.example.springboot.testspringconfig;import com.example.springboot.configuration.SpringConfig;import com.example.springboot.model.JiaoZi;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class TestSpringConfig {@Testpublic void testPropertiesSource(){ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);JiaoZi jiaoZi = (JiaoZi) applicationContext.getBean("jiaozi");System.out.println("food: " + jiaoZi);}}

    经验总结扩展阅读