Spring 裝配Bean 基於註解
阿新 • • 發佈:2018-12-17
註解:就是一個類,使用@註解名稱 開發時:我們使用註解 取代 xml配置檔案。
1 @Component取代<bean class="">
@Component(“id”) 取代 <bean id="" class="">
2.web開發,提供3個@Component註解衍生註解(功能一樣)取代
@Repository :dao層
@Service:service層
@Controller:web層
3.依賴注入 ,給私有欄位設定,也可以給setter方法設定
普通值:@Value("")
引用值:
方式1:按照【型別】注入
@Autowired
方式2:按照【名稱】注入1
@Autowired
@Qualifier(“名稱”)
方式3:按照【名稱】注入2
@Resource(“名稱”)
4.生命週期
初始化:@PostConstruct
銷燬:@PreDestroy
5.作用域
@Scope(“prototype”) 多例
註解使用前提,新增名稱空間,讓spring掃描含有註解類
<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" >
<!-- 元件掃描,掃描含有註解的類 -->
<context:component-scan base-package="com.g_annotation.a_ioc"></context:component-scan>
</beans>