Spring Bean裝配方式

Spring裝配機制

  • 在xml中進行顯示配置
  • 在Java中進行顯示配置
  • 隱式bean發現機制和自動裝配

自動化裝配bean

  • 組件掃描(component scanning),Spring會自動發現應用上下文中的bean
  • 自動裝配(autowiring),Spring自動知足bean之間的依賴

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

經過java代碼裝配bean

  • 建立配置類並標記 @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

經過xml裝配bean

  • 建立Spring Xml配置文件
  • 在JavaConfig中導入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();
    }
}
相關文章
相關標籤/搜索