Spring學習 ---- 創建Bean的四種方式

創建Bean的四種方式


反射調用構造方法創建對象

 <bean id="bean1" class="com.github.excellent.Bean1">

 </bean>
  • Bean對象所處的類中,一定要含有一個無參的構造方法,否則會報錯。因爲這個方式的本質就是調用反射中的class.newInstance()方法。
  • 對於某些別人提供的jar包,不能確定類中是否有默認的構造方法,因此不能採取這種方式創建Bean對象。

使用工廠中的方法創建對象(使用某個類中的方法創建對象)

   <!--先配置工廠,包括id,class-->
    <bean id="computerFactory" class="com.github.excellent.testdi.ComputerFactory">

    </bean>

    <!--再配具體的類,屬性工廠bean,工廠中的方法-->
    <bean id="computers" factory-bean="computerFactory" factory-method="getInstance">

    </bean>

  • 配置bean的工廠類id class
  • 配置bean類屬性包括id,factory-bean ,和factory-method

使用靜態工廠中的靜態方法創建Bean對象

 <bean id="bean1" class="com.github.excellent.BeanFactory" factory-method="getInstance">

  </bean>
  • 配置beanFactory,註明方法。

使用註解創建Bean對象

@Data
@Component(value = "computer")
@ComponentScan(value = "com.github.excellent.testdi")
public class Computer {
    private String name;
    private double proice;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章