一 基于 注解 的方式 初始化 spring 容器

当我们不使用spring的时候 完成一个简单的 打印机任务是这样的

//MessageService类 只提供 打印内容 
public class MessageService {

    public MessageService() {
        super();
        System.out.println("MessageSerivce.....");
    }

    public String getMessage(){
        return "Hello World!!!";
    }
}
//MessagePrinter类 通过传递 Server 来提供简单的打印服务 
public class MessagePrinter {

    private MessageService service;

    public MessagePrinter() {
        super();
        System.out.println("MessagePrinter.....");
    }

    public void printMessage(){
        System.out.println(this.service.getMessage());
    }

    public void setService(MessageService service) {
        this.service = service;
    }
}
public static void main(String[] args) {
			// 创建一个service 实例
        	MessageService service  = new MessageService();
        	// 创建一个printer 实例
        	MessagePrinter printer = new MessagePrinter();
        	//将service传递给 printer
        	printer. setService(service)
        	//就可以完成打印任务
        	printer.printMessage();
 }

这样每次都需要手动创建实例

而现在我们使用spring来管理这些类 让这些任务变的简单

基于注解的方式初始化spring容器

在需要spring管理的类上方添加注解@Component
@Component //该注解 spring 自动为类创建实例对象
public class MessageService {
	......
}

  • 函数入口处添加ComponentScan注解
  • ComponentScan(组件扫描)
  • 该注解扫描所有包含 @Component 注解的类 所有含有@Component注解的类都会被扫描到
  • spring会将 这些类的实例创建到当前类中

@ComponentScan 
public class Application {
    public static void main(String[] args) {
    		......
    }
}

下面开始 初始化 spring 容器
  • AnnotationConfigApplicationContext() 该类需要传递一个类对象
  • 该类对象是添加过 @ComponentScan 注解(spring容器)的 类对象

 ApplicationContext context = new AnnotationConfigApplicationContext( Application.class );

 /*这个时候spring容器已经初始化成功 所有被扫描到的 包含@Component注解的 类对象都会被初始化出来
 所有被扫描到的 包含@Component注解的类中的 构造方法 都会被调用*/

  • 从容器中获取 MessagePrinter对象

//调用 printer.getBean() 方法获取 bean 对象 
MessagePrinter printer = context.getBean( MessagePrinter.class ); //获取printer对象

MessageService service = context.getBean(MessageService.class); //获取service对象

printer.setService(service); //传递service对象
printer.printMessage();

转自@发际线男孩

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值