Spring帮助我们创建对象
package hello;
import org.springframework.stereotype.Component;
/**
* 获取消息
*
* @author ChenHanlu at 2019-12-08
*/
/*这个类不需要new关键字创建,可以由Spring管理,自动加载*/
@Component
public class MessageService {
public MessageService() {
super();
System.out.println("初始化MessageService!");
}
public String getMessage() {
return "Hello word!";
}
}
package hello;
import org.springframework.stereotype.Component;
/**
* 打印功能
*/
@Component
public class MessagePrinter {
public MessagePrinter() {
super();
System.out.println("初始化MessagePrinter!");
}
/*初始化服务*/
private MessageService service;
/**
* 设置服务
*/
public void setService(MessageService service) {
this.service = service;
}
/*打印功能*/
public void printMessage() {
System.out.println(this.service.getMessage());
}
}
package hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
/*组建扫描Component,扫描到之后,自动创建到Spring容器中
* Spring容器所在的位置就是,ComponentScan类所在的位置
* */
@ComponentScan
public class ApplicationSpring {
public static void main(String[] args) {
/*初始化Spring容器,
Spring中所有的Compent也会被初始化出来*/
ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationSpring.class);
/* 初始化Bean对象*/
MessagePrinter printer = context.getBean(MessagePrinter.class);
MessageService service = context.getBean(MessageService.class);
/* 调用函数*/
printer.setService(service);
printer.printMessage();
}
}
网友评论