JavaEE Spring框架的介绍 2.IOC的程序入门

创建Java工程,导入坐标依赖

<dependencies>
 <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>5.0.2.RELEASE</version>
 </dependency>
 <dependency>
     <groupId>commons-logging</groupId>
     <artifactId>commons-logging</artifactId>
     <version>1.2</version>
 </dependency>
 <dependency>
     <groupId>log4j</groupId>
     <artifactId>log4j</artifactId>
     <version>1.2.12</version>
 </dependency>
 <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.12</version>
     <scope>test</scope>
 </dependency>
 </dependencies>

编写接口和实现类,编写具体的实现方法

packagecom.qcbyjy.service;
 ​
 public interface UserService{
 ​
     public void hello();
 ​
 }
 ​
 ​
 package com.qcbyjy.service;
 ​
 public class UserServiceImpl implements UserService{
     @Override
     public void hello(){
         System.out.println("HelloIOC!!");
     }
 }

编写Spring核心的配置文件,在src目录下创建applicationContext.xml的配置 文件,名称是可以任意的,但是一般都会使用默认名称。

<?xmlversion="1.0"encoding="UTF-8"?>
 <beansxmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans.xsd">
 <!--IOC管理bean-->
     <beanid="userService"class="com.qcbyjy.service.UserServiceImpl"/>
 </beans>

把log4j.properties的配置文件拷贝到resources目录下,做为log4j的日志配置 文件。

编写测试方法。

package com.qcbyjy.test;
 ​
 import com.qcbyjy.service.UserService;
 import org.junit.Test;
 import org.springframework.context.ApplicationContext;
 import
 org.springframework.context.support.ClassPathXmlApplicationContext;
 ​
 public class Demo1{
 ​
 /**
 *入门程序
*/
 @Test
 public void run1(){
 //使用Spring的工厂
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
 //通过工厂获得类:
     UserService userService=(UserService) applicationContext.getBean("userService");
     userService.hello();
     }
 ​
 }

ApplicationContext接口,工厂的接口,使用该接口可以获取到具体的Bean对 象。该接口下有两个具体的实现类。springCould配置中心

ClassPathXmlApplicationContext,加载类路径下的Spring配置文件。 FileSystemXmlApplicationContext,加载本地磁盘下的Spring配置文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值