標籤:*** tail .class 姓名 love 商務邏輯層 容器管理 index turn
一、基於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:表示資料訪問層的組件
@Servicepublic class SysUserService { @Resource private SysUserMapper sysUserMapper; public int insertSelective(SysUser record){ return sysUserMapper.insertSelective(record); }}三、基於Java類的配置
適用情境:
- 需要通過代碼控制對象建立邏輯的情境
- 實現零配置,消除xml設定檔
步驟如下:
- 使用@Configuration註解需要作為配置的類,表示該類將定義Bean的中繼資料
- 使用@Bean註解相應的方法,該方法名預設就是Bean的名稱,該方法傳回值就是Bean的對象。
- 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; } }
public class Main { public static void main(String args[]){ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeansConfiguration.class); Student student = (Student) context.getBean("student"); Teacher teacher = (Teacher) context.getBean("teacher"); System.out.println("學生的姓名:" + student.getName() + "。老師是" + student.getTeacher().getName()); System.out.println("老師的姓名:" + teacher.getName()); } }
參考:78524489
Spring Bean定義的三種方式