Spring-03-利用注解配置应用IOC

来源:互联网 发布:24小时私人网络上借钱 编辑:程序博客网 时间:2024/06/05 05:49

在JDK5.0时追加一些新特性
List<String>
for(String s : list){ }
Integer i = 10;

注解:在类定义,方法定义,成员变量定义前面使用
格式:@注解标记名

a.组件自动扫描
b.注入注解


组件自动扫描

可以按指定的包路径,将包下所有组件扫描。如果发现组件类定义前有以下标记,会将组件扫描到Spring容器。
@Component//其他组件
@Controller//控制层组件
@Service//业务层组件xxxService
@Repository//数据访问层组件xxxDAO

@Scope控制对象创建,默认单例
@PostConstruct指定init-method
@PreDestroy指定destroy-method

@Named(需要引入第三方标准包)


在.xml文件中,开启组件扫描。扫描org.tarena包下的组件

.xml文件中:<!-- 开启组件扫描 -->    <context:component-scan base-package="org.tarena"/>

ExampleBean类

@Component//扫描ExampleBean组件,默认id=exampleBean@Scope("singleton")//控制单例singleton, 非单例prototype,等价于<bean scope="...">public class ExampleBean {    @PostConstruct//初始化,等价于<bean lazy-init="true" init-method="init">    public void init(){        System.out.println("初始化逻辑");    }    @PreDestroy//等价于<bean destroy-method="destroy">    public void destroy(){        System.out.println("释放资源");    }    public void execute(){        System.out.println("执行execute()方法");    }}

ExampleBean1类,可以指定id 的名字

@Component("exam1")//指定id=exam1public class ExampleBean1 {    public void execute(){        System.out.println("执行execute()方法");    }}

注入注解

@Resource:标记写在变量定义前,或者set方法定义前
@Autowired:与@Resource一样

注意:
1. 如果标记写在变量前,则set方法可以省略
2.一般使用时,功能等价,都可以实现注入
如果不存在多个匹配类型,两个都可以使用
如果存在多个匹配类型,建议按名称注入
@Resource(name=”指定名称”)或
@Autowired
@Qualifier(“p”)


set注入建议用@Resource
构造器建议用@Autowired


Computer类

@Component("c")public class Computer {    public void show(){        System.out.println("显示电脑配置信息");    }}

Phone类

@Component("p")public class Phone {    public void show(){        System.out.println("显示手机配置信息");    }}

Student类
需要注入Computer和Phone对象
@Resource标记
@Autowired

public class Student {    //需要调用Computer和Phone对象    //注入Computer对象    @Resource    private Computer c;    public void setC(Computer c) {        this.c = c;    }    //注入Phone对象    @Autowired    private Phone p;    public void setP(Phone p) {        this.p = p;    }    public void show(){        System.out.println("显示学生信息");        c.show();        p.show();    }}

测试类

public class TestIOC {    public static void main(String[] args){        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        Student s = (Student)ac.getBean("s");        s.show();    }}


SpringIOC应用:
自己写的组件建议使用注解配置;
框架API只能用XML配置

0 0
原创粉丝点击