使用工具:idea2018.3 ,maven3.6
step.1
maven倚赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
step.2
创建服务类:
- 创建接口 MessageService
public interface MessageService {
String getMessage();
}
- 实现接口类:MessageServiceImpl
@Service
public class MessageServiceImpl implements MessageService {
public String getMessage() {
return "Hello World!";
}
}
- 其中Service(和后面的Component)注解该类是一个spring bean
step.3
创建打印器MessagePrinter :
@Component
public class MessagePrinter {
final private MessageService service;
@Autowired
public MessagePrinter(MessageService service) {
this.service = service;//通过Autowired,将MessageService自动注入
}
public void printMessage() {
System.out.println(this.service.getMessage());
}
}
step.4
创建应用主类:
@ComponentScan
public class Application {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
MessagePrinter printer = context.getBean(MessagePrinter.class);
printer.printMessage();
}
}
- 其中MessagePrinter ,不需要通过new来实例化,而是直接从spring容器中取出
- AnnotationConfigApplicationContext是上下文的一种实现方式
- @ComponentScan会扫描指定包下的所有标有@Component的类,并装配为bean