自动化装配Bean
Posted gede
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自动化装配Bean相关的知识,希望对你有一定的参考价值。
一、创建 CompactDisc接口和SgetPeppers实现类
CompactDisc接口方法为播放。SgtPeppers实现CompactDisc接口。
1 package soundsystem; 2 3 public interface CompactDisc { 4 void play(); 5 6 }
1 package soundsystem; 2 3 import org.springframework.stereotype.Component; 4 //component为spring中bean扫描标识 5 @Component 6 public class SgtPeppers implements CompactDisc { 7 8 private String title = "歌德"; 9 private String artist = "gede"; 10 11 public void play() { 12 System.out.println("Playing " + title + " by " + artist); 13 } 14 15 }
二、启用spring组件扫描
1、通过java配置启用
添加 @Configuration @ComponentScan 两个注解即可。
【注】使用ComponentScan时,若配置文件和bean在同一个包,省略基础包备注也可以。
1 package soundsystem; 2 import org.springframework.context.annotation.ComponentScan; 3 import org.springframework.context.annotation.Configuration; 4 5 @Configuration 6 @ComponentScan("soundsystem") 7 public class JavaConfig { 8 9 }
2、通过xml配置启用:<context:component-scan base-package="soundsystem"></context:component-scan> 如果没有自动提示或者报错,在namespace中添加context配置
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <context:component-scan base-package="soundsystem"></context:component-scan> </beans>
三、编写测试类,并运行
1、创建test包,分别通过java配置和xnl配置实现测试
java配置为:AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(soundsystem.JavaConfig.class);
xml配置为:ClassPathXmlApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml");
1 package test; 2 3 import org.springframework.context.annotation.AnnotationConfigApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 import soundsystem.CompactDisc; 6 import soundsystem.SgtPeppers; 7 8 public class Test { 9 public static void main(String[] args) { 10 //基于java类中配置上下文 11 //AnnotationConfigApplicationContext context = 12 new AnnotationConfigApplicationContext(soundsystem.JavaConfig.class); 13 //基于xml配置上下文 14 ClassPathXmlApplicationContext context = 15 new ClassPathXmlApplicationContext("applicationContext.xml"); 16 17 CompactDisc cd=context.getBean(SgtPeppers.class); 18 cd.play(); 19 } 20 }
以上是关于自动化装配Bean的主要内容,如果未能解决你的问题,请参考以下文章