文件具体格式
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd">
<!-- 去包下扫描对应的注解组件,如果有多个包需要被扫描;只需要用逗号隔开多个包 -->
<context:component-scan base-package="ioc"></context:component-scan>
<!-- 解析Resource Autowired注解 -->
<context:annotation-config></context:annotation-config>
</beans>
otherbean类
package ioc;
import org.springframework.stereotype.Component;
@Component("otherbean")
public class otherbean {
}
somebean类
package ioc;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
//<bean id="somebean" class="ioc.somebean" init-method="open" destroy-method="close"></bean>近似等价于@Component
@Component("somebean")
@Scope("singleton")//作用域
public class somebean {
@Resource(name = "otherbean")
private otherbean bean;
// @PostConstruct:用于贴在初始化方法上
//@PreDestroy用于贴在销毁方法上
//初始化方法,构造器之后执行
@PostConstruct
public void open(){
System.out.println("少年贪玩,青年迷恋爱情,壮年汲汲于成名成家,暮年自安于自欺欺人。");
}
//销毁方法,在销毁操作执行前执行
@PreDestroy
public void close(){
System.out.println("名声,活着也许对自己有用,死后只能被人利用了。");
}
public void sayhello(){
System.out.println(". 一个人经过不同程度的锻炼,就获得不同程度的修养、不同程度的效益。好比香料,捣得愈碎,磨得愈细,香得愈浓烈。我们曾如此渴望命运的波澜,到最后才发现:人生最曼妙的风景,竟是内心的淡定与从容……我们曾如此期盼外界的认可,到最后才知道:世界是自己的,与他人毫无关系!");
}
@Override
public String toString() {
return "somebean{" +
"bean=" + bean +
'}';
}
}
test方法测试类
package ioc;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class test {
@Resource
private somebean bean;
@Test
public void test(){
System.out.println(bean);
bean.sayhello();
}
}
测试结果