IOC註解的使用
1,導入依賴和添加約束
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" 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">
<!-- bean definitions here -->
</beans>
2,添加組件掃描
掃描該包下的所有組件
<context:component-scan base-package="包名"/>
3,Spring框架中Bean管理的常用註解
@Component(value="userService")
相當於在XML的配置方式中
<bean id="userService" class="...">
4,Spring框架中Bean管理的常用註解
4.1,組件注入
- @Component:組件(作用在類上)
- Spring中提供@Component的三個衍生註解
- @Controller:作用在WEB層
- @Service:作用在業務層
- @Repository:作用在持久層
這三個註解是爲了讓標註類本身的用途清晰,Spring在後續版本會對其增強
4.2,屬性注入
- 注入普通類型
- @Value:用於注入普通類型
- 注入對象類型
- @Autowired:默認按類型進行自動裝配
- @Qualifier:強制使用名稱注入
- @Resource:相當於@Autowired和@Qualifier一起使用
- Java提供的註解
- 屬性使用name屬性
5,Bean的作用範圍和生命週期的註解
Bean的作用範圍註解
- 註解爲@Scope(value=”prototype”),作用在類上。
- singleton – 單例,默認值
- prototype – 多例
- 註解爲@Scope(value=”prototype”),作用在類上。
Bean的生命週期的配置(瞭解)
- @PostConstruct – 相當於init-method
- @PreDestroy – 相當於destroy-method
6,Spring框架整合JUnit單元測試
6.1,在程序中引入:spring-test.jar
6.2,在具體的測試類上添加註解
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml")
public class SpringDemo1 {
@Resource(name="userService")
private UserService userService;
@Test
public void demo2(){
userService.save();
}
}