您的位置:首页 > 编程语言 > Java开发

Spring中用注解实现bean的定义以及作用域

2016-03-22 23:23 537 查看
 在spring中,有关bean的设置不仅可以通过xml来实现,还可以用注解直接在代码中实现

第一步:配置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/beans

        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context

        http://www.springframework.org/schema/context/spring-context.xsd" >

       

        <context:component-scan base-package="com.imooc.beanannotation"></context:component-scan>

       

 </beans>

 

中间类

package com.imooc.beanannotation;

import org.springframework.context.annotation.Scope;

import org.springframework.stereotype.Component;

@Scope("prototype")

@Component("bean")

public class BeanAnnotation {

  public void say(String arg)

  {

   System.out.println(arg);

  }

}

测试类

package com.imooc.beanannotation;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBeanAnnotation {

public static void main(String[] args) {

 

  ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-beanannotation.xml");

  BeanAnnotation bean=ctx.getBean("bean",BeanAnnotation.class);

  BeanAnnotation bean2=ctx.getBean("bean",BeanAnnotation.class);

  bean.say("this is a test");

System.out.println(bean.hashCode());

System.out.println(bean2.hashCode());

 

}

}

可以看见,我们并未配置xml,这是单单用注解就实现的bean的配置。

常见的定义bean的注解有:Component(通用)Repository(持久层)Service(服务层)Controller(控制层)

我们通过Scope注解定义bean的作用域,prototype与singgleton多例与单例
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: