天天看點

Bean管理注解方式,建立對象

幾個注解:@Component. @Service. @Controller. @Reposttory

注解是代碼特殊标記;注解在類上面,方法上面,屬性上面;使用注解是為了簡化xml配置

整體流程:

測試方法:
@Test
    public void testService(){
        //1.加載配置檔案,配置檔案中隻有一句話,加載元件掃描,然後到配置的包中找到包中所有類,,如果類上面有相關的注解,就根據注解把相關的對象建立。

        ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);//getBean的内容原來是id的值,現在就是Component注釋的value值
        System.out.println(userService);//輸出對象
        userService.add();//調用對象類裡的add方法

配置檔案:
  <context:component-scan base-package="com.company"></context:component-scan>

包中類的編寫:
@Component(value = "userService") //<bean id="userSevice" class="">
//注解裡value屬性值可以不寫,預設值是類名稱(首字母小寫)
public class UserService {
    public void add(){
        System.out.println("service add...");
    }
}
           
加載配置檔案,配置檔案中隻有一句話,加載元件掃描,然後到配置的包中找到包中所有類,,如果類上面有相關的注解,就根據注解把相關的對象建立。      
元件掃描細節配置
<!--執行個體1
   use-default-filters="false 表示不使用預設的filter,自己配置filter
   context:include-filter 設定掃描哪些内容。type=annotation,表示根據注解來掃描 帶Component注解的
   -->
   <context:component-scan base-package="com.company" use-default-filters="false">
      <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
   </context:component-scan>

   <!--執行個體2
   下面配置掃描包内所有内容,但是不掃描用Controller注解的内容
   -->
   <context:component-scan base-package="com.company" >
      <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
   </context:component-scan>