spring使用注解的方式創建bean ,將組件加入容器中


第一種使用@Bean的方式

1、創建一個bean

package com.springbean;

public class Person {

    private  String name;
    private Integer age ;

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

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

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

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

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

2、創建配置類:
 
        
import com.springbean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PersonConfig {

    @Bean
  //@Bean("myperson") 這是設置bean的名字 public Person person(){
   System.out.println("已經創建實例");
   return new Person("張三",20); } }
 
        
3、測試
import com.spring.config.PersonConfig;
import com.springbean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ApplicationTest {
    public static void main(String[] args) {
        
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);

    //獲取bean的類型,默認是方法名,需要修改就在配置類中@Bean里面加上名字
    String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
    for (String beanType : beanNamesForType){
    System.out.println(beanType);
    }
  } 
}

和xml配置文件一樣,默認的bean是單例的,如果需要改變為prototype,xml配置文件里是加上scope="prototype",這里PersonConfig配置類中需要加上注解@Scope("prototype")。
介紹一下bean的幾種類型的作用域。
  • singleton:單實例(默認),ioc容器啟動時就會創建對象放到ioc容器中,以后每次獲取都是直接從ioc容器中獲取,ioc容器可以簡單理解為map
  • prototype:多實例(原型),ioc容器啟動並不會去調用方法創建對象,而是每次我們獲取對象的時候,才會調用方法去創建。
  • requst:同一次請求創建一個實例
  • session:同一個session創建一個實例
不加注解測試:
 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
        Person bean = applicationContext.getBean(Person.class);
        Person bean2 = applicationContext.getBean(Person.class);
        System.out.println(bean==bean2);
//打印結果為true
 
        

加上注解@Scope("prototype")測試:

 

 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
        Person bean = applicationContext.getBean(Person.class);
        Person bean2 = applicationContext.getBean(Person.class);
        System.out.println(bean==bean2);
//打印結果為fale

 

我們也可以改變單例時ioc加載的時候就創建實例,只要在我們的PersonConfig配置類中加上@Lazy注解,使用懶加載。測試

public class ApplicationTest {
    public static void main(String[] args) {

        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
       /* Person bean = applicationContext.getBean(Person.class);
        Person bean2 = applicationContext.getBean(Person.class);
        System.out.println(bean==bean2);*/
    /*
        String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
        for (String beanType : beanNamesForType){
            System.out.println(beanType);
        }*/
    }
}

這是時打印欄將不會打印出“已經創建實例”,就實現的單例情況下的懶加載。

 

 第二種使用@import注解的方式

新建一個student類

public class Student {
}

 

在配置類PersonConfig上使用@Import注解,這里面可以傳入一個數組,用大括號{}

@Configuration
@Import({Student.class})
public class PersonConfig {

 測試:

public class DemoTest {

    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);

    @Test
    public void test(){

        Student bean = applicationContext.getBean(Student.class);
        System.out.println(bean);

    }
}

打印結果:com.springbean.Student@2c34f934 ,注入成功

 

 還可以在@Import中加入ImportSelector的實現類來實現bean的注入

創建Parent和Teacher類

public class Parent {
}

public class Teacher {
}

 

創建ImportSelector的實現類MyImportSelector,返回需要注入的bean,這里是全類名

public class myImportSelector implements ImportSelector{
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {

        return new String[]{"com.springbean.Parent","com.springbean.Teacher"};
    }
}

修改PersonConfig,這里傳入實現類MyImportSelector

@Configuration
@Import({Student.class, myImportSelector.class})
public class PersonConfig {

測試:

     Parent parent = applicationContext.getBean(Parent.class);
        Teacher teacher = applicationContext.getBean(Teacher.class);
        System.out.println(parent);
        System.out.println(teacher);

 打印結果:

com.springbean.Parent@3b2cf7ab
com.springbean.Teacher@2aa5fe93

 

 第三種使用@ComponentScan的方式:

@Configuration
@ComponentScan("com.springbean")
public class MainBeanConfig  {

}

指定需要掃描包的路徑,相應的類中加上組件注解。

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM