javascript
Spring教程--IOC(注解方式)和整合junit
1 IOC裝配Bean(注解方式)
1.1?Spring的注解裝配Bean
Spring2.5 引入使用注解去定義Bean
@Component ?描述Spring框架中Bean
?
Spring的框架中提供了與@Component注解等效的三個(gè)注解:
@Repository 用于對(duì)DAO實(shí)現(xiàn)類進(jìn)行標(biāo)注
@Service 用于對(duì)Service實(shí)現(xiàn)類進(jìn)行標(biāo)注
@Controller 用于對(duì)Controller實(shí)現(xiàn)類進(jìn)行標(biāo)注
?
1.2?Bean的屬性注入:
普通屬性:
@Value(value="sihai")private String info;?
對(duì)象屬性:
@Autowired:自動(dòng)裝配默認(rèn)使用類型注入.
@Qualifier("userDao")--- 按名稱進(jìn)行注入.
?
@Qualifier("userDao")private UserDao userDao;等價(jià)于@Resource(name="userDao")private UserDao userDao;1.3?Bean其他的屬性的配置:
配置Bean初始化方法和銷毀方法:
init-method 和 destroy-method.
@PostConstruct 初始化
@PreDestroy ?銷毀
?
配置Bean的作用范圍:
@Scope
1.4?Spring3.0提供使用Java類定義Bean信息的方法
@Configurationpublic class BeanConfig {@Bean(name="car")public Car showCar(){Car car = new Car();car.setName("長(zhǎng)安");car.setPrice(40000d);return car;}@Bean(name="product")public Product initProduct(){Product product = new Product();product.setName("空調(diào)");product.setPrice(3000d);return product;}}1.5?實(shí)際開發(fā)中使用XML還是注解
XML:
bean管理
注解;
注入屬性的時(shí)候比較方便.
?
兩種方式結(jié)合;一般使用XML注冊(cè)Bean,使用注解進(jìn)行屬性的注入.
?
<context:annotation-config/>@Autowired@Qualifier("orderDao")private OrderDao orderDao;2?Spring整合web開發(fā)
正常整合Servlet和Spring沒(méi)有問(wèn)題的
但是每次執(zhí)行Servlet的時(shí)候加載Spring配置,加載Spring環(huán)境.
解決辦法:在Servlet的init方法中加載Spring配置文件
?將加載的信息內(nèi)容放到ServletContext中.ServletContext對(duì)象時(shí)全局的對(duì)象.服務(wù)器啟動(dòng)的時(shí)候創(chuàng)建的.在創(chuàng)建ServletContext的時(shí)候就加載Spring的環(huán)境.
?ServletContextListener:用于監(jiān)聽ServletContext對(duì)象的創(chuàng)建和銷毀的.
?
2.1 導(dǎo)入
?? spring-web-3.2.0.RELEASE.jar
2.2 在web.xml中配置
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param>修改程序的代碼:
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());WebApplicationContext applicationContext = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);3?Spring集成JUnit測(cè)試
3.1.程序中有Junit環(huán)境.
3.2.導(dǎo)入一個(gè)jar包.spring與junit整合jar包.
?? spring-test-3.2.0.RELEASE.jar
3.3測(cè)試代碼:
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations="classpath:applicationContext.xml")public class SpringTest {@Autowiredprivate UserService userService;@Testpublic void demo1(){userService.sayHello();}}《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀
總結(jié)
以上是生活随笔為你收集整理的Spring教程--IOC(注解方式)和整合junit的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Spring教程--IOC(控制反转)详
- 下一篇: Spring教程--AOP简介