組件掃描:Spring能夠從classpath下自動掃描,偵測和實例化具有特定注解的組件。
特定組件包括:
1、@Component:基本注解,識別一個受Spring管理的組件
2、@Respository:標識持久層組件
3、@Service:標識業務層組件
4、@Controller:標識表現層組件
Spring 有默認的命名策略: 使用非限定類名, 第一個字母小寫. 也可以在注解中通過 value 屬性值標識組件的名稱
當在組件類上使用了特定的注解之后, 還需要在 Spring 的配置文件中聲明<context:component-scan> :
1、base-package 屬性指定一個需要掃描的基類包,Spring 容器將會掃描這個基類包里及其子包中的所有類.
2、當需要掃描多個包時, 可以使用逗號分隔.
3、<context:include-filter />和<context:exclude-filter />
1 <!-- 掃描@Controller注解 --> 2 <context:component-scan base-package="com.hzg.controller" use-default-filters="false"> 3 <context:include-filter type="annotation"expression="org.springframework.stereotype.Controller" /> 4 </context:component-scan> 5 6 <!-- 配置掃描注解,不掃描@Controller注解 --> 7 <context:component-scan base-package="com.hzg.controller"> 8 <context:exclude-filter type="annotation"expression="org.springframework.stereotype.Controller" /> 9 </context:component-scan>
當使用<context:include-filter />的時候,在<context:component-scan >里必須加上use-default-filters="false",否則不起作用。
其中屬性expression的值不是你的包所在位置,別搞錯了,它是你注解的具體類地址。
實例:
創建包com.hzg.anotation
創建包com.hzg.anotation.controller
創建UserController類
1 @Controller 2 public class UserController { 3 4 @Autowired(required = false) 5 private UserService userService; 6 //@Autowired也可以放在setter方法上,那就去掉上面的Autowired注解 7 public void setUserService(UserService userService) { 8 this.userService = userService; 9 } 10 11 public void excute(){ 12 System.out.println("UserController excute"); 13 userService.diao(); 14 } 15 }
創建包com.hzg.anotation.service
創建UserService類
1 @Service 2 public class UserService { 3 4 @Autowired 5 private UserRepostory userRepostory; 6 public void diao(){ 7 System.out.println("UserService diao"); 8 userRepostory.save(); 9 } 10 }
創建包com.hzg.anotation.repostory
創建UserRepostory接口
1 public interface UserRepostory { 2 void save(); 3 }
創建UserRepostoryImlp類
1 @Repository("userRepostory") 2 public class UserRepostoryImlp implements UserRepostory { 3 4 @Override 5 public void save() { 6 System.out.println("UserRepostory save"); 7 } 8 }
創建configautowire.xml文件
1 <context:component-scan base-package="com.hzg.anotation"></context:component-scan>
Main方法
1 public static void main(String[] args) { 2 ApplicationContext ctx = new ClassPathXmlApplicationContext("configautowire.xml"); 3 UserController userController = (UserController) ctx.getBean("userController"); 4 userController.excute(); 5 }
輸出接口:
UserController excute
UserService diao
UserRepostory save
其中:
1、@Autowired(required = false)中required = false的意思是:如果沒有這個類的實例化,那么會賦值成NULL,而不是報錯。
2、@Autowired注解可以為成員變量、方法、構造函數賦值。
3、@Repository("userRepostory")等同於@Repository(value = "userRepostory"),value是默認值,代表給這個Bean
賦值了id的值,防止有重復的Bean。
4、如果在UserService類的@Autowired下面使用限定修飾符@Qualifier("userRepostoryImlp"),那么
@Repository("userRepostory")必須寫成@Repository或者寫成@Repository("userRepostoryImlp"),否則就有歧義了。
------------------------------------------------------------------------------------------------------------------------