Spring-IOCの基本:アノテーションインジェクション(ライトバージョン)

<h1>準備

<h3>エンティティクラス

package demo.spring.entity;
public class UserInfo {
	 public void init() {
	 	 System.out.println("init method");
	 } 
 }

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw ==

サービスクラス

package demo.spring.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import demo.spring.entity.UserInfo;

@Service
public class TestService {
	
	@Autowired private UserInfo user;
	
	public void test() {
		user.init();
	}

}

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw ==

 

 

テストクラス

package demo.spring.test;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import demo.spring.service.TestService;


public class DemoTest {
	
	@Test
	public void test01() {
		ApplicationContext conf = new ClassPathXmlApplicationContext("BeanIocDemo.xml");
		TestService ts = conf.getBean(TestService.class);
		ts.test();
	}
	
}

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw ==

xmlファイル

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"
	>
 
  
<!--  id="example" -->
 <bean class="demo.spring.entity.UserInfo"></bean>
 
 <!--service  -->
 <context:component-scan base-package="demo.spring.service"/>
 
 
 
</beans>

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw ==効果:

test01メソッドを実行すると、コンソールはUserInfoにinitメソッドを出力します

 

元の記事を22件公開 いいね3 ビジター3442

おすすめ

転載: blog.csdn.net/ChyoD1811/article/details/90480564
おすすめ