入門
/**
* 賬戶的業務層實現類
* @author 黑馬程序員
* @Company http://www.ithiema.com
* @Version 1.0
*/
@Component("accountService")
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
}
/**
* 賬戶的持久層實現類
* @author 黑馬程序員
* @Company http://www.ithiema.com
* @Version 1.0
*/
@Component("accountDao")
public class AccountDaoImpl implements IAccountDao {
private DBAssit dbAssit;
}
注意:
當我們使用註解注入時,set 方法不用寫。
注意:
基於註解整合時,導入約束時需要多導入一個 context 名稱空間下的約束。
由於我們使用了註解配置,此時不能在繼承 JdbcDaoSupport,需要自己配置一個 JdbcTemplate
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 告知 spring 創建容器時要掃描的包 -->
<context:component-scan base-package="com.itheima"></context:component-scan>
</beans>
1、 用於創建對象的註解
相當於:<bean id="" class="">
@Component
作用:
把資源讓 spring 來管理。相當於在 xml 中配置一個 bean。
屬性:
value:指定 bean 的 id。如果不指定 value 屬性,默認 bean 的 id 是當前類的類名。首字母小寫。
@Controller @Service @Repository
他們三個註解都是針對一個的衍生註解,他們的作用及屬性都是一模一樣的。
他們只不過是提供了更加明確的語義化。
@Controller:一般用於表現層的註解。
@Service:一般用於業務層的註解。
@Repository:一般用於持久層的註解。
細節:如果註解中有且只有一個屬性要賦值時,且名稱是 value,value 在賦值是可以不寫。
2、 用於注入數據的
相當於:
<property name="" ref="">
<property name="" value="">
@Autowired
作用:
自動按照類型注入。當使用註解注入屬性時,set 方法可以省略。它只能注入其他 bean 類型。當有多個
類型匹配時,使用要注入的對象變量名稱作爲 bean 的 id,在 spring 容器查找,找到了也可以注入成功。找不到
就報錯。
@Qualifier
作用:
在自動按照類型注入的基礎之上,再按照 Bean 的 id 注入。它在給字段注入時不能獨立使用,必須和
@Autowire 一起使用;但是給方法參數注入時,可以獨立使用。
屬性:
value:指定 bean 的 id。
@Resource
作用:
直接按照 Bean 的 id 注入。它也只能注入其他 bean 類型。
屬性:
name:指定 bean 的 id。
@Value
作用:
注入基本數據類型和 String 類型數據的
屬性:
value:用於指定值
3、用於改變作用範圍的:
相當於:<bean id="" class="" scope="">
@Scope
作用:
指定 bean 的作用範圍。
屬性:
value:指定範圍的值。
取值:singleton prototype request session globalsession