spring bean的註冊(一)

內容提要:

  1. 學習spring容器需要導入的jar包
  2. 學習spring bean註冊進容器的兩種方式: xml方式和註解方式@Configuration
  3. 學習註解方式的@Bean註解
  4. 學習註解方式的@ComponentScan(包掃描)

一. 創建maven項目, 引入spring容器jar包

spring-context包是學習spring框架的基礎包, 先引入:

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>4.3.12.RELEASE</version>
</dependency>

二. 創建一個Javabean

public class Person implements Serializable {

    private static final long serialVersionUID = -3665665049573500448L;

    private String name;
    private Integer age;

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Person() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

三. 使用xml文件的方式將一個Javabean實例註冊到容器中

1. 創建xml文件

在resource文件夾下創建一個spring格式的xml文件, 可以使用bean標籤或註解掃描將實例註冊到容器

<?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"
       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">

    <!--使用bean標籤往容器中註冊一個對象-->
    <bean id="person" class="com.xxx.bean.Person" scope="xxxx" lazy-init="xxxx">
        <property name="age" value="18"/>
        <property name="name" value="zhangsan"/>
    </bean>

    <!-- 使用註解掃描, 將指定包下的帶有註解類型(@controller, @service, @repository, @component)的類, 放進spring容器中進行管理-->
    <!--<context:component-scan base-package="com.xxx.bean"/>-->

</beans>
  1. scope: 作用域
  • singleton 在spring IoC容器僅存在一個Bean實例,Bean以單例方式存在,默認值
  • prototype 每次從容器中調用Bean時,都返回一個新的實例,即每次調用getBean()時,相當於執行newXxxBean()
  • request 每次HTTP請求都會創建一個新的Bean,該作用域僅適用於WebApplicationContext環境
  • session 同一個HTTP Session共享一個Bean,不同Session使用不同的Bean,僅適用於WebApplicationContext環境
  • global-session 一般用於Portlet應用環境,該運用域僅適用於WebApplicationContext環境
  1. lazy-init: 決定該實例是否是在容器啓動時被初始化
    參數1. true 延遲加載, 當使用這個對象時, 才被初始化
    參數2. false 當容器啓動時, 對象被初始化(默認)

2. 測試

2.1 使用junit測試, 引入jar包

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

scope標籤
參數1. compile 默認的scope,表示 dependency 都可以在生命週期中使用。而且,這些dependencies 會傳遞到依賴的項目中。適用於所有階段,會隨着項目一起發佈
參數2. provided 跟compile相似,但是表明了dependency 由JDK或者容器提供,例如Servlet AP和一些Java EE APIs。這個scope 只能作用在編譯和測試時,同時沒有傳遞性。
參數3. runtime 表示dependency不作用在編譯時,但會作用在運行和測試時,如JDBC驅動,適用運行和測試階段。
參數4. test 表示dependency作用在測試時,不作用在運行時。 只在測試時使用,用於編譯和運行測試代碼。不會隨項目發佈。
參數5. system 跟provided 相似,但是在系統中要以外部JAR包的形式提供,maven不會在repository查找它。

2.1 創建測試類

public class SpringXMLTest {

    @Test
    public void test01() {
        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        Person person = (Person) applicationContext.getBean("person");
        System.out.println(person);
    }
}

ClassPathXmlApplicationContext 類路徑下, 就是編譯後classes文件夾下, 相對路徑

四. 使用註解的方式將一個Javabean註冊到容器中

核心註解: @Configuration
4.1 創建一個配置類

@Configuration
@ComponentScan("com.xxxx")
public class BeanConfig {

    @Bean("person")
    @Scope("prototype")
    @Lazy
    public Person getPerson() {
        System.out.println("註冊person...");
        return new Person("laowang", 20);
    }

}

4.2 創建測試類

public class SpringAnnotationTest {

    @Test
    public void test01() {
        AbstractApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
        String[] names = applicationContext.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
        Person person = (Person) applicationContext.getBean("person");
        Person person2 = (Person) applicationContext.getBean("person");
        System.out.println(person == person2);

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章