//注解方式可以簡化spring的ioc容器的配置
使用注解步驟:
1、先引入context名稱空間
xmlns:context=“http://www.springframework.org/schema/context”
2、開啟注解掃描
<context:component-scan base-package=“com.huawei.sdn”></context:component-scan>
3、使用注解:通過注解的方式,把對象加入ioc容器。
@Component 指把一個對象加入IOC容器
@Repository 作用通@Component;在持久層使用dao
@Service 作用同@Component;在業務邏輯層使用service
@Controller 作用通@Component;在控制層使用action、
@Resource 屬性注入
@Resource(name=“屬性名/變量名”) 根據名稱查找,優先使用
@Resource 根據類型查找
@Component(“userDao”) 把目前對象加入ioc容器
@Component 加入ioc容器的UserDao對象的引用名稱,預設與類名一樣,且第一個字母小寫
4、Autowried注入,注解看用于成員變量,setter方法,構造函數等。
@Autowired預設按照類型比對的方式進行注入
@Autowired使用時,須有且有僅有一個與之比對的bean,當找不到比對的bean或者存在多個比對的bean時,spring容器将抛出異常。
5、spring 允許通過@Qualifier注釋指定注入的bean的名稱
6、@Autowired和@Qualifier結合使用時,自動注入的政策就從byType轉變成byName了。
7、@Resource作用相當于@Autowired,隻不過@Autowired按byType自動注入,@Rource預設按byName自動注入罷了。
//注解使用關鍵字@interface,繼承java.lang.annotition.Annotition。
8、@Repository等同于配置檔案中
@Service(value=“testServcie”)
public class TestService(){
System.our.printIn(“testService test”);
}
9、@Resource
@Resource對象間關系的組合,預設采用的是byName方式進行裝配的,如果根據名稱查找不到關聯的對象,那麼會再采用byType繼續查找。
10、@Controller
@Controller(value=“ua”)
@Scope(value=“prototype”)
public class UserAction{
@Resource
private UserService userServcie;
public UserService getUserServcie(){
return userService;
}
}