1.2 spring的helloworld应用
戴着假发的程序员 出品
[查看视频讲解]
[1]准备
创建项目:spring-st
添加依赖:
1 <dependencies> 2 <dependency> 3 <groupId>org.springframework</groupId> 4 <artifactId>spring-context</artifactId> 5 <version>5.1.3.RELEASE</version> 6 </dependency> 7 <dependency> 8 <groupId>junit</groupId> 9 <artifactId>junit</artifactId> 10 <version>4.12</version> 11 <scope>test</scope> 12 </dependency> 13 </dependencies>
添加AccountDAO类:
1 package com.boxuewa.dk.demo1.dao; 2 3 /** 4 * @author 戴着假发的程序员 5 * @description 6 */ 7 public class AccountDAO { 8 public int save(String name){ 9 System.out.println("AccountDAO-save->保存账户:"+name); 10 return 1; 11 } 12 }
添加AccountService类:
1 package com.boxuewa.dk.demo1.service; 2 3 import com.boxuewa.dk.demo1.dao.AccountDAO; 4 5 /** 6 * @author 戴着假发的程序员 7 * 8 * @description 9 */ 10 public class AccountService { 11 private AccountDAO accountDAO; 12 public void setAccountDAO(AccountDAO accountDAO) { 13 this.accountDAO = accountDAO; 14 } 15 public int save(String name){ 16 System.out.println("AccountService-save->保存用户:"+name); 17 return accountDAO.save(name); 18 } 19 }
AccountService中依赖了AccountDAO,提供setAccountDAO方法,spring会通过这个方法注入accountDAO对象。
添加spring配置文件,并且注册AccountService和AccountDAO
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 <!-- 注册accountDAO --> 7 <bean id="accountDAO" class="com.boxuewa.dk.demo1.dao.AccountDAO"> 8 </bean> 9 <!-- 注册accountService --> 10 <bean id="accountService" class="com.boxuewa.dk.demo1.service.AccountService"> 11 <!-- 给accountService注入属性accountDAO --> 12 <property name="accountDAO" ref="accountDAO"/> 13 </bean> 14 </beans>
项目整体结构如下:
添加测试类,创建spring容器进行测试:
1 /** 2 * @author 戴着假发的程序员 3 * 4 * @description 5 */ 6 public class SpringTest1 { 7 @Test 8 public void testSpringHellowrod(){ 9 //创建spring容器 10 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); 11 AccountService bean = ac.getBean(AccountService.class); 12 bean.save("卡卡西"); 13 } 14 }
测试结果:
我是戴着假发的程序员,分享技术,分享经验,如果要转载,请注明:出自戴着假发的程序员