Spring中用注解实现bean的定义以及作用域
来源:互联网 发布:网络数据采集有什么用 编辑:程序博客网 时间:2024/04/27 16:08
在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多例与单例
- Spring中用注解实现bean的定义以及作用域
- Spring-Bean的定义装配以及作用域的注解实现
- Spring Bean装配之Bean的定义及作用域的注解实现
- Spring入门(Bean的定义及作用域的注解实现)
- Spring Bean装配:Bean注解实现以及定义
- Spring注解实现Bean定义
- Spring注解实现Bean定义
- Spring注解实现Bean定义
- spring入门(注解实现Bean的定义)
- 使用Spring注解完成Bean的定义
- 使用Spring注解完成Bean的定义
- 注解实现Bean定义
- Spring整理系列(11)——@Configuration注解、@Bean注解以及配置自动扫描、bean作用域
- Spring中bean的定义及其作用域
- Spring IOC--Bean的装配(使用注解定义Bean)
- Spring IOC--Bean的装配(使用注解定义Bean)
- Spring-基于注解的配置[01定义Bean+扫描Bean]
- Spring学习,Bean作用范围以及生命过程方法的注解
- 每天算法01
- Android Studio 安装及常见问题
- 【杭电oj】5620 - KK's Steel(递推)
- ThinkPHP 分页类
- linux文本处理三剑客
- Spring中用注解实现bean的定义以及作用域
- BestCoder #76
- React-Native系列Android——自定义View组件开发
- Objective c ,iOS KVC是如何实现的,权威答案
- Codeforces 653E:Bear and Forgotten Tree 2
- Oracle数据库学习(三)--基础查询及关联查询
- Eclipse安装颜色主题插件eclipse color theme
- python学习(二):函数
- Mac 10.12.1 安装cocoapods(淘宝镜像用不了的)