先 autowired
autowired 之后再执行
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
class A {
void print() {
System.out.println("A");
}
}
@Component
class B {
@Autowired
A a;
@PostConstruct
void init() {
a.print();
}
}
@SpringBootApplication
public class DemoApplication {
@Autowired
B b;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
本文介绍了一个使用Spring Boot框架实现依赖注入的例子。通过两个组件类A和B,演示了如何利用@Autowired注解完成类A到类B的依赖注入,并在B类中通过@PostConstruct注解的方法初始化时调用类A的方法。同时,在主类DemoApplication中也展示了如何自动装配B类。
1239

被折叠的 条评论
为什么被折叠?



