Spring Bean定義的三種方式

Spring Bean定義的三種方式

 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

一、基於XML的配置

適用場景:

  • Bean實現類來自第三方類庫,如:DataSource等
  • 需要命名空間配置,如:context,aop,mvc等
<beans>
<import resource=“resource1.xml” />//導入其他配置文件Bean的定義
<import resource=“resource2.xml” />

<bean id="userService" class="cn.lovepi.***.UserService" init-method="init" destory-method="destory"> 
</bean>
<bean id="message" class="java.lang.String">
  <constructor-arg index="0" value="test"></constructor-arg>
</bean>
</beans>

二、基於註解的配置

適用場景:

項目中自己開發使用的類,如controller、service、dao等

步驟如下:

1. 在applicationContext.xml配置掃描包路徑

<context:component-scan base-package="com.lovepi.spring"> 
  <context:include-filter type="regex" expression="com.lovepi.spring.*"/>   //包含的目標類
  <context:exclude-filter type="aspectj" expression="cn.lovepi..*Controller+"/>   //排除的目標類
</context:component-scan>

注:context:component-scan/ 其實已經包含了 context:annotation-config/的功能

2. 使用註解聲明bean

Spring提供了四個註解,這些註解的作用與上面的XML定義bean效果一致,在於將組件交給Spring容器管理。組件的名稱默認是類名(首字母變小寫),可以自己修改:

  • @Component:當對組件的層次難以定位的時候使用這個註解
  • @Controller:表示控制層的組件
  • @Service:表示業務邏輯層的組件
  • @Repository:表示數據訪問層的組件
@Service
public class SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    public int insertSelective(SysUser record){
        return sysUserMapper.insertSelective(record);
    }

}

三、基於Java類的配置

適用場景:

需要通過代碼控制對象創建邏輯的場景 實現零配置,消除xml配置文件

步驟如下:

  1. 使用@Configuration註解需要作爲配置的類,表示該類將定義Bean的元數據
  2. 使用@Bean註解相應的方法,該方法名默認就是Bean的名稱,該方法返回值就是Bean的對象。
  3. AnnotationConfigApplicationContext或子類進行加載基於java類的配置
@Configuration  
public class BeansConfiguration {  

    @Bean  
    public Student student(){  
        Student student=new Student();  
        student.setName("張三");  
        student.setTeacher(teacher());  
        return student;  
    }  

    @Bean  
    public Teacher teacher(){  
        Teacher teacher=new Teacher();  
        teacher.setName("李四");  
        return teacher;  
    }  

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