日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring教程--IOC(注解方式)和整合junit

發布時間:2025/3/20 javascript 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring教程--IOC(注解方式)和整合junit 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1 IOC裝配Bean(注解方式)

1.1?Spring的注解裝配Bean

Spring2.5 引入使用注解去定義Bean

@Component ?描述Spring框架中Bean

?

Spring的框架中提供了與@Component注解等效的三個注解:

@Repository 用于對DAO實現類進行標注

@Service 用于對Service實現類進行標注

@Controller 用于對Controller實現類進行標注


?

1.2?Bean的屬性注入:

普通屬性:

@Value(value="sihai")private String info;

?

對象屬性:

@Autowired:自動裝配默認使用類型注入.

@Qualifier("userDao")--- 按名稱進行注入.

?

@Qualifier("userDao")private UserDao userDao;等價于@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("長安");car.setPrice(40000d);return car;}@Bean(name="product")public Product initProduct(){Product product = new Product();product.setName("空調");product.setPrice(3000d);return product;}}

1.5?實際開發中使用XML還是注解

XML:

bean管理

注解;

注入屬性的時候比較方便.

?

兩種方式結合;一般使用XML注冊Bean,使用注解進行屬性的注入.

?

<context:annotation-config/>@Autowired@Qualifier("orderDao")private OrderDao orderDao;


2?Spring整合web開發

正常整合Servlet和Spring沒有問題的

但是每次執行Servlet的時候加載Spring配置,加載Spring環境.

解決辦法:在Servlet的init方法中加載Spring配置文件

?將加載的信息內容放到ServletContext中.ServletContext對象時全局的對象.服務器啟動的時候創建的.在創建ServletContext的時候就加載Spring的環境.

?ServletContextListener:用于監聽ServletContext對象的創建和銷毀的.

?

2.1 導入

?? 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測試


3.1.程序中有Junit環境.


3.2.導入一個jar包.spring與junit整合jar包.

?? spring-test-3.2.0.RELEASE.jar


3.3測試代碼:

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations="classpath:applicationContext.xml")public class SpringTest {@Autowiredprivate UserService userService;@Testpublic void demo1(){userService.sayHello();}}

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的Spring教程--IOC(注解方式)和整合junit的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。