使用注解简化Ioc

 

 

文件具体格式

 

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();

}

}

 

 

 

 

测试结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值