Speak.javajava
public interface Speak { void say(); }
ChineseSpeak.javaspring
@Component("chineseSpeak") public class ChineseSpeak implements Speak { public void say() { System.out.println("用中文說"); } }
SpeakConfig.javaspa
@Component @ComponentScan(basePackages = "com.xqh.spring.autowire") public class SpeakConfig { }
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpeakConfig.class) public class SpeakTest { @Autowired private Speak speak; @Test public void sayTest(){ speak.say(); } }
@Component註解告訴Spring這是一個組件類併爲之建立bean,bean的id爲首字母變小寫的類名code
@ComponentScan註解啓用組件掃描並默認掃描與配置類相同的包component
@Autowired註解會在Spring上下文中在自動裝配符合的beanxml
建立配置類並標記 @Configuration註解對象
建立方法標記 @Bean註解it
Speak.java自動化
public interface Speak { void say(); }
ChineseSpeak.javaio
public class ChineseSpeak implements Speak { public void say(){ System.out.println("經過java代碼裝配-用中文說"); } }
SpeakConfig.java
@Configuration public class SpeakConfig { @Bean public Speak chineseSpeak() { return new ChineseSpeak(); } }
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpeakConfig.class) public class SpeakTest { @Autowired private Speak speak; @Test public void sayTest(){ speak.say(); } }
@Configuration標記的類表名是一個配置類而且包含在Spring上下文中如何建立bean的細節
@Bean註解告訴Spring這個方法將返回一個對象而且註冊爲Spring上下文中的bean
Speak.java
public interface Speak { void say(); }
ChineseSpeak.java
public class ChineseSpeak implements Speak { public void say() { System.out.println("經過xml裝配bean-用中文說"); } }
SpeakConfig.java
@Configuration @ImportResource("classpath:spring-beans.xml") public class SpeakConfig { }
spring-beans.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="chineseSpeak" class="com.xqh.spring.xmlconfig.ChineseSpeak"></bean> </beans>
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpeakConfig.class) public class SpeakTest { @Autowired private Speak speak; @Test public void sayTest(){ speak.say(); } }