Spring(三)注解装配
来源:互联网 发布:蒙古语翻译软件 编辑:程序博客网 时间:2024/06/09 15:38
Spring装配Bean之最终法宝-注解装配!
使用注解标识Bean
这个标签指定包下的类可以使用集中注解表明这个类为Spring Bean
- @Component 是一个泛化的概念,仅仅表示一个组件 (Bean) ,可以作用在任何层次。
- @Service 通常作用在业务层,但是目前该功能与 @Component 相同。
- @Constroller 通常作用在控制层,但是目前该功能与 @Component 相同。
- @Repository 注解便属于最先引入的一批,它用于将数据访问层 (DAO 层 ) 的类标识为 Spring Bean。
1、配置文件
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 开启注解 --> <!-- <context:annotation-config /> --> <!-- 开启自动扫描Bean,有了自动扫描,可以不用开启注解! --> <context:component-scan base-package="com.zh" /> <!--针对zh以下的包都可使用--> </beans>
2、JavaBean
@Componentpublic class Flashlight { @Value("2") //赋初始值 private int num; @Autowired //byType //@Qualifier("mybattery") //指定byName private Battery battery; public void shine() { System.out.println("照明使用"+num+"节"); battery.supplyPowerPoint(); } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public Battery getBattery() { return battery; } public void setBattery(Battery battery) { this.battery = battery; }}
备注:这里需要注意一个问题,注解装配ID默认为类型头字母小写,如Student类,它的ID就是student;
@Componentpublic class Battery { public void supplyPowerPoint(){ System.out.println("电池"); }}
测试类
public class AnnotationTest {public ApplicationContext applicationContext; public AnnotationTest() { //读取配置文件 applicationContext=new ClassPathXmlApplicationContext("com/zh/annotation/springannotation.xml"); } //注解装配Bean public void annatationBean(){ Flashlight flashlight=(Flashlight) applicationContext.getBean("flashlight"); flashlight.shine(); } //测试 public static void main(String[] args) { AnnotationTest test=new AnnotationTest(); test.annatationBean(); }}
阅读全文
0 0
- Spring(三)注解装配
- Spring 学习(三)注解装配
- Spring(三、Spring Bean自动装配和注解注入)
- spring 注解装配
- Spring使用注解装配
- spring 注解 自动装配
- spring装配 注解
- Spring事务-注解--装配文件
- spring注解自动装配Bean
- Spring---IOC应用(注解装配)
- Spring 使用注解装配Bean
- Spring 使用注解自动装配
- spring-装配Bean 基于注解
- Spring的《注解装配》- @autowired
- spring装配bean(基于注解)
- Spring自动装配(注解)
- Spring 装配Bean 基于注解
- Spring注解方式装配Bean
- golang版本protobuf 在windows系统下安装环境
- Oracle_第四弹
- 单例模式的七种写法
- Linux system Apache
- 如何利用EndNote,在word中插入参考文献
- Spring(三)注解装配
- 回到顶部按钮
- 第16章 Sun RPC
- idea中编码快捷键
- css3 居中定位方法
- 设计模式--单例模式
- MFC树形控件CTreeCtrl使用方法、遍历、SetCheck无效、根据名称获取节点、获取选中节点等问题
- ecshop中$user对象
- [Android]Error:Failed to open zip file.Gradle's dependency cache may be corrupt.