<h1>准备
<h3>实体类
package demo.spring.entity;
public class UserInfo {
public void init() {
System.out.println("init method");
}
}
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();
}
}
测试类
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();
}
}
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>
效果:
运行test01方法, 控制台打印了 UserInfo 中的 init方法