@Component
Compent等效于xml文件中的Bean标注,Autowired自动初始化Bean是通过查找Component注解实现的,在增加Component后还是Autowired找不到的情况,应该是在main类中没有增加ComponentScan注解。
@SpringBootApplication @ComponentScan(basePackages = "com.xes.cloudlearn.requester.producter") public class TestApplication { public static void main(String[] args){ SpringApplication.run(TestApplication.class,args); } }
@ConfigurationProperties 读取配置文件
ConfigurationProperties注解用于标注读取配置文件的节点,PropertySource用于标注文件,如果PropertySource不设置,默认读取application.properties或application.yml文件。
@Component("queueConfiguration") @ConfigurationProperties(prefix = "requester.rocketmq", ) public class QueueConfiguration { private String rocketHost; public String getRocketHost() { return rocketHost; } public void setRocketHost(String rocketHost) { this.rocketHost = rocketHost; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } private String topic; }
调用配置文件
@Component("queueProducter") public class QueueProducter { @Autowired QueueConfiguration queueConfiguration; public void SendQueue(){ System.out.println(queueConfiguration.getRocketHost()); } }
测试用例
@RunWith(SpringRunner.class) @SpringBootTest(classes=TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) public class QueueProducterTest { @Autowired QueueProducter queueProducter; @Test public void testQueue(){ System.out.println(">>>>>>>>>>>>>> testing..."); queueProducter.SendQueue(); } }