Spring通过main方法启动

一直以来都是J2EE开发,编写Service、Controller,启动tomcat服务,然后采用HTTP方式访问。很长一段时间以为Spring必须在web工程下才能使用(尴尬得很),直到后来系统学习了Spring的容器。


Spring ApplicationContext 容器

Spring 提供了以下两种不同类型的容器接口。

1 Spring BeanFactory 容器
它是最简单的容器,给 DI 提供了基本的支持,它用> org.springframework.beans.factory.BeanFactory 接口来定义。BeanFactory> 或者相关的接口,如 BeanFactoryAware,InitializingBean,DisposableBean,在 Spring> 中仍然存在具有大量的与 Spring 整合的第三方框架的反向兼容性的目的。
2 Spring ApplicationContext 容器
该容器添加了更多的企业特定的功能,例如从一个属性文件中解析文本信息的能力,发布应用程序事件给感兴趣的事件监听器的能力。该容器是由
org.springframework.context.ApplicationContext 接口定义。

最常被使用的 ApplicationContext 接口实现:

AnnotationConfigApplicationContext: 从一个或多个基于Java的配置类中加载Spring应用上下文。

AnnotationConfigWebApplicationContext: 从一个或多个基于Java的配置类中加载Spring Web应用上下文。

ClassPathXmlApplicationContext: 从类路径下的一个或多个XML配置文件中加载上下文定义, 把应用上下文的定义文件作为类资源。

FileSystemXmlapplicationcontext: 从文件系统下的一个或多个XML配置文件中加载上下文定义。

XmlWebApplicationContext: 从Web应用下的一个或多个XML配置文件中加载上下文定义。

ClassPathXmlApplicationContext部分UML图如下:
在这里插入图片描述
使用示例(Spring实战4):

 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/soundsystem.xml");
        MediaPlayer player = context.getBean(MediaPlayer.class);
        player.play();

AnnotationConfigApplicationContext部分UML图。
在这里插入图片描述
使用示例(Spring实战4):

   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(CDPlayerConfig.class);
        ctx.register(CDPlayerConfig.class);
        MediaPlayer player = ctx.getBean(MediaPlayer.class);
        player.play();

完整示例(Spring实战4第一章节源码扩展学习)

package soundsystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CDPlayer implements MediaPlayer {
  private CompactDisc cd;

  @Autowired
  public CDPlayer(CompactDisc cd) {
    this.cd = cd;
  }

  public void play() {
    cd.play();
  }

}

package soundsystem;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class CDPlayerConfig { 
}

package soundsystem;

public interface CompactDisc {
  void play();
}

package soundsystem;

public class ExportDocxLoop implements Runnable {

    @Override
    public void run() {

    }
}

package soundsystem;

public interface MediaPlayer {

  void play();

}

package soundsystem;
import org.springframework.stereotype.Component;

@Component
public class SgtPeppers implements CompactDisc {

  private String title = "Sgt. Pepper's Lonely Hearts Club Band";  
  private String artist = "The Beatles";
  
  public void play() {
    System.out.println("Playing " + title + " by " + artist);
  }
  
}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="soundsystem"/>

</beans>

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringMainFun {

    //看W3cschool里的例子
    public void xmlrun() {
        //new ClassPathXmlApplicationContext 参数不能为空
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/soundsystem.xml");
        MediaPlayer player = context.getBean(MediaPlayer.class);
        player.play();

    }

    /*
     *  AnnotationConfigApplicationContext ctx =
     *    new AnnotationConfigApplicationContext();
     *    ctx.register(AppConfig.class, OtherConfig.class);
     *    ctx.register(AdditionalConfig.class);
     *    ctx.refresh();
     *    MyService myService = ctx.getBean(MyService.class);
     *    myService.doStuff();
     */
    public void annotationRun() {
        //new AnnotationConfigApplicationContext 参数不能为空
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(CDPlayerConfig.class);
        ctx.register(CDPlayerConfig.class);
        MediaPlayer player = ctx.getBean(MediaPlayer.class);
        player.play();
    }

    public void threadRun() {
        //new AnnotationConfigApplicationContext 参数不能为空
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(CDPlayerConfig.class);
        ctx.register(CDPlayerConfig.class);
        MediaPlayer player = ctx.getBean(MediaPlayer.class);
        System.out.println("容器启动完成,开始处理------");
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i =0;i<10 ;i++){
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    player.play();
                }
            }
        }).start();
    }

    public static void main(String[] args) {
        new SpringMainFun().threadRun();
    }
}

踩坑记录

Exception in thread “main” java.lang.IllegalStateException: org.springframework.context.annotation.AnnotationConfigApplicationContext@3f91beef has not been refreshed yet
at org.springframework.context.support.AbstractApplicationContext.assertBeanFactoryActive(AbstractApplicationContext.java:1069)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1093)
at soundsystem.SpringMainFun.annotationRun(SpringMainFun.java:30)
at soundsystem.SpringMainFun.main(SpringMainFun.java:56)

原因:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
解决:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(CDPlayerConfig.class);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值