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配置
- Spring-03-利用注解配置应用IOC
- Spring IoC 注解配置
- Spring IoC 注解配置
- Spring---IOC应用(注解装配)
- Spring IOC配置与应用
- Spring IOC配置与应用
- Spring复习(二)IOC注解配置
- 注解方式配置Spring实现Ioc
- 通过注解方式配置Spring的IoC
- spring中注解配置IOC失败异常
- Spring 基于注解的IOC配置
- 通过注解方式配置Spring实现Ioc
- Spring IOC 之注解配置、单元测试
- spring的配置及ioc注解总结
- Spring中IOC配置xml实现和IOC注解实现
- 利用注解配置Spring容器
- Spring IOC 常用注解
- Spring IOC 常用注解
- Android中paddingleft(),layout_marginleft(),getleft(),getright()的一些区别
- notification点击跳转的两种情况
- JAVA-static关键字
- Access restriction: The type BASE64Decoder is not accessible
- 第十周项目3--利用二叉树遍历思想解决问题
- Spring-03-利用注解配置应用IOC
- ARM寄存器介绍
- bzoj 2002 [Hnoi2010]Bounce 弹飞绵羊 [分块][特殊处理]
- 将sublime text3添加到右键菜单中(可执行)
- oracle中case when then及decode用法
- 责任链模式
- usaco Milking Cows (贪心)
- NOIP2015 写后感
- C# & WPF 随手小计之一 ——初探async await 实现多线程处理