溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring中怎么利用注解的方式創(chuàng)建bean

發(fā)布時(shí)間:2021-07-24 14:35:28 來源:億速云 閱讀:141 作者:Leah 欄目:編程語言

Spring中怎么利用注解的方式創(chuàng)建bean,相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

第一種使用配置類的方式

1、創(chuàng)建一個(gè)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、創(chuàng)建配置類:

import com.springbean.Person;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class PersonConfig {  @Bean  //@Bean("myperson") 這是設(shè)置bean的名字  public Person person(){   System.out.println("已經(jīng)創(chuàng)建實(shí)例");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的類型,默認(rèn)是方法名,需要修改就在配置類中@Bean里面加上名字    String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);    for (String beanType : beanNamesForType){      System.out.println(beanType);    }  } }

和xml配置文件一樣,默認(rèn)的bean是單例的,如果需要改變?yōu)閜rototype,xml配置文件里是加上scope="prototype",這里PersonConfig配置類中需要加上注解@Scope("prototype")。

介紹一下bean的幾種類型的作用域。

singleton:單實(shí)例(默認(rèn)),ioc容器啟動(dòng)時(shí)就會(huì)創(chuàng)建對象放到ioc容器中,以后每次獲取都是直接從ioc容器中獲取,ioc容器可以簡單理解為map  prototype:多實(shí)例(原型),ioc容器啟動(dòng)并不會(huì)去調(diào)用方法創(chuàng)建對象,而是每次我們獲取對象的時(shí)候,才會(huì)調(diào)用方法去創(chuàng)建。  requst:同一次請求創(chuàng)建一個(gè)實(shí)例  session:同一個(gè)session創(chuàng)建一個(gè)實(shí)例

不加注解測試:

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);    Person bean = applicationContext.getBean(Person.class);    Person bean2 = applicationContext.getBean(Person.class);    System.out.println(bean==bean2);//打印結(jié)果為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);//打印結(jié)果為fale

我們也可以改變單例時(shí)ioc加載的時(shí)候就創(chuàng)建實(shí)例,只要在我們的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);    }*/  }}

這是時(shí)打印欄將不會(huì)打印出“已經(jīng)創(chuàng)建實(shí)例”,就實(shí)現(xiàn)的單例情況下的懶加載。

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

新建一個(gè)student類

public class Student {}

在配置類PersonConfig上使用@Import注解,這里面可以傳入一個(gè)數(shù)組,用大括號(hào){}

@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);  }}

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

還可以在@Import中加入ImportSelector的實(shí)現(xiàn)類來實(shí)現(xiàn)bean的注入

創(chuàng)建Parent和Teacher類

public class Parent {}public class Teacher {}

創(chuàng)建ImportSelector的實(shí)現(xiàn)類MyImportSelector,返回需要注入的bean,這里是全類名

public class myImportSelector implements ImportSelector{  @Override  public String[] selectImports(AnnotationMetadata annotationMetadata) {    return new String[]{"com.springbean.Parent","com.springbean.Teacher"};  }}

修改PersonConfig,這里傳入實(shí)現(xiàn)類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);

打印結(jié)果:

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

看完上述內(nèi)容,你們掌握Spring中怎么利用注解的方式創(chuàng)建bean的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI