POM
ハロー春という名前のプロジェクトを作成pom.xml
、次の書類を:
1 |
<?xml version = "1.0"エンコード= "UTF-8"?> <プロジェクトのxmlns = "http://maven.apache.org/POM/4.0.0" のxmlnsを:XSI = "のhttp://www.w3 .ORG / 2001 / XMLスキーマ・インスタンス」 のxsi:のschemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion> 4.0.0 </ modelVersion> <のgroupId> com.funtl </のgroupId> <たartifactId>ハロースプリング</たartifactId> <バージョン> 1.0.0-SNAPSHOT </バージョン> <パッケージ>ジャー</包装> <依存性> <依存> <groupIdを> org.springframework </ groupIdを> <たartifactId>ばねコンテキスト</たartifactId> </依存関係> <バージョン> 4.3.17.RELEASE </バージョン> </依存関係> </プロジェクト>
|
コアパッケージ:主要な増加org.springframework:春、コンテキスト依存
インタフェースと実装の作成
UserServiceのインターフェイスの作成
1 |
パッケージcom.funtl.hello.spring.service。 パブリック インターフェースUserServiceの{ 公共 ボイドsayHi(); }
|
UserServiceImplを達成するための作成
1 |
パッケージcom.funtl.hello.spring.service.impl。 輸入com.funtl.hello.spring.service.UserService。 パブリッククラスUserServiceImplはUserServiceの{実装し ます。public void sayHi(){ System.out.printlnは( "こんにちは春"); } }
|
Spring構成ファイルを作成します。
ではsrc/main/resources
、ディレクトリの作成spring-context.xml
プロファイルを、次のように今から春容器管理(IOC)、コンフィギュレーションファイルにクラスの仕事をインスタンス化します。
1 |
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="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"> <bean id="userService" class="com.funtl.hello.spring.service.impl.UserServiceImpl" /> </beans>
|
<bean />
:用于定义一个实例对象。一个实例对应一个 bean 元素。
id
:该属性是 Bean 实例的唯一标识,程序通过 id 属性访问 Bean,Bean 与 Bean 间的依赖关系也是通过 id 属性关联的。
clas
s:指定该 Bean 所属的类,注意这里只能是类,不能是接口。
测试 Spring IoC
创建一个 MyTest
测试类,测试对象是否能够通过 Spring 来创建,代码如下:
1 |
package com.funtl.hello.spring; import com.funtl.hello.spring.service.UserService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { public static void main(String[] args) { // 获取 Spring 容器 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml"); // 从 Spring 容器中获取对象 UserService userService = (UserService) applicationContext.getBean("userService"); userService.sayHi(); } }
|