没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
Java之之Spring注解配置注解配置bean实例代码解析实例代码解析
主要介绍了Java之Spring注解配置bean实例代码解析,具有一定参考价值,文中还有有关Spring学习的资料下载
链接及相关内容推荐,需要的朋友可以了解下。
前面几篇均是使用xml配置bean,如果有上百个bean,这是不可想象的。故而,请使用注解配置bean !!!
【【1】注解类别】注解类别
@Component : 基本注解, 标识了一个受 Spring(点击这里可以下载《Spring应用开发完全手册》) 管理的组件
@Repository : 标识持久层组件
@Service : 标识服务层(业务层)组件
@Controller : 标识表现层组件
Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件。
对于扫描到的组件, Spring 有默认的命名策略: 使用非限定类名, 第一个字母小写. 也可以在注解中通过 value 属性值标识组件
的名称
【【2】】context:component-scan
当在组件类上使用了特定的注解之后, 还需要在 Spring 的配置文件中声明 <context:component-scan/> ::base-package 属
性指定一个需要扫描的基类包,Spring 容器将会扫描这个基类包里及其子包中的所有类。
当需要扫描多个包时, 可以使用逗号分隔,如果仅希望扫描特定的类而非基包下的所有类,可使用 resource-pattern 属性过滤
特定的类。示例:
<context:component-scan base-package="com.web.annotation" resource-pattern="repository/*.class"
use-default-filters="true">
<context:include-filter> 子节点表示要包含的目标类
<context:exclude-filter> 子节点表示要排除在外的目标类
<context:component-scan> 下可以拥有若干个 <context:include-filter> 和 <context:exclude-filter> 子节点
一个复杂的一个复杂的<context:component-scan/>
如下配置将只扫描repository下的包:resource-pattern="repository/*.class"
默认fileter(use-default-filters="true")将扫描所有注解组件,若想使用 include-filter等,则将其改为false.
<context:component-scan base-package="com.web.annotation" resource-pattern="repository/*.class"
use-default-filters="true">
<!-- 只包含Repository注解 ,其他不行-->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>-->
<!-- 不包含Repository注解 ,其他可以-->
<!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>-->
<!-- 只包含Repository接口及其实现类 ,其他不行-->
<!-- <context:include-filter type="assignable" expression="com.web.annotation.repository.UserRepository"/>-->
<!-- 不包含Repository接口及其实现类 ,其他可以-->
<!-- <context:exclude-filter type="assignable" expression="com.web.annotation.repository.UserRepository"/>-->
</context:component-scan>
【【3】代码中引用其他】代码中引用其他bean,简单示例如下:,简单示例如下:
@Resource(name="userRepository")
private UserRepository repository;
public void add(){
System.out.println("UserService add...");
repository.save();
}
引用其他bean有如下几种方式:
@Autowired 和 @Resource 、@Inject
【【4】使用】使用 @Autowired 自动装配自动装配 Bean
@Autowired 注解自动装配具有兼容类型的单个 Bean属性,构造器, 普通字段(即使是非 public), 一切具有参数的方法都可以应
用@Authwired 注解
默认按类型匹配,若一个类型多个实现,将会自动查询注解定义的名字,先匹配。若实现类注解都没有定义名字,将会抛出异
常!!
1)默认情况下, 所有使用 @Authwired 注解的属性都需要被设置。
资源评论
weixin_38747216
- 粉丝: 5
- 资源: 882
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功