您的位置:首页 > 编程语言 > Java开发

基于java配置启动spring容器

2015-11-06 09:39 681 查看

     spring容器的启动方式有很多种,基本分两大类,一 是在XML中配置bean的信息,二基本java配置启动spring容器。今天主要介绍一下基本java配置启动spring容器的方式

一、基本XML的配置方式启动spring容器,常见的有两种方式

1、通过BeanFactory的方式启动spring容器

 ResourcePatternResolver rpr=new PathMatchingResourcePatternResolver();
  Resource resource=rpr.getResource(path);
  beanFactory=new XmlBeanFactory(resource);

ac.getBean(beanName);

注:这里的path可以通过通配符的方式加载  classpath:*.xml

 

2.通过ApplicationContext的方式启动spring容器

ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:*.xml");

ac.getBean(beanName);

 

二、基本java配置启动spring容器

1、类名需要用@Configuration进行注解。创建AnnotationConfigApplicationContext类,注册用@Configuration注解的类,调用refresh()方法刷新spring容器的注册配置。具体的看代码:

 

@Configuration
public class Beans {
 
 //喜欢的运动   sport就是spring窗口中bean的名称
 @Bean
 public List<String> sport(){
  List<String> sports=new ArrayList();
  sports.add("打蓝球");
  sports.add("踢足球");
  return sports;
 }
 
 //幸运数字  luckyNum就是spring窗口中bean的名称
 @Bean
 public List<Integer> luckyNum(){
  List<Integer> lucky=new ArrayList();
  lucky.add(3);
  lucky.add(8);
  return lucky;
 }
 
 //@Test   第一种启动方式
 public void test01(){
  ApplicationContext ac=new AnnotationConfigApplicationContext(Beans.class);
  List<String> sports=(List<String>)ac.getBean("sport");
  System.out.println("我喜欢的运动:"+sports);
  List<Integer> lucky=(List<Integer>)ac.getBean("luckyNum");
  System.out.println("幸运数字:"+lucky);
 }
 
 @Test  //第二种启动方式
 public void test02(){
  AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext();
  //注册一个@Configuration配置类
  ac.register(Beans.class);
  //刷新容器以应用这些注册的配置类
  ac.refresh();
  List<String> sports=(List<String>)ac.getBean("sport");
  System.out.println("我喜欢的运动:"+sports);
  List<Integer> lucky=(List<Integer>)ac.getBean("luckyNum");
  System.out.println("幸运数字:"+lucky);
 }

}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐