为了账号安全,请及时绑定邮箱和手机立即绑定

【备战春招】第19天 Spring入门

标签:
Java

课程名称:Spring入门

课程章节:第4章 注解的基本使用介绍

课程讲师: 西昆仑

课程内容:

1、属性的继承

1.1、多个Class是继承某一个ParentClass

代码示例:

//spring.xml

<bean class="com.imooc.spring.ioc.class12.ParentClass" abstract="true" id="parentClass"/>

<property name="attribute1" value="attribute1"/>

<property name="attribute2" value="attribute2"/>

<property name="attribute3" value="attribute3"/>

</bean>

<bean class="com.imooc.spring.ioc.class12.Class1" id="class1" parent="parentClass"/>

<property name="attribute4" value="attribute4"/>

<property name="attribute5" value="attribute5"/>

</bean>

<bean class="com.imooc.spring.ioc.class12.Class2" id="class2" parent="parentClass"/>

<property name="attribute7" value="attribute7"/>

<property name="attribute8" value="attribute8"/>

</bean>

运行结果:

https://img1.sycdn.imooc.com//63fa19720001e06214500814.jpg

1.2、多个Class无继承的ParentClass

代码示例:

//spring.xml,差异点,删除ParentClass

<bean abstract="true" id="parentClass"/>

<property name="attribute1" value="attribute1"/>

<property name="attribute2" value="attribute2"/>

<property name="attribute3" value="attribute3"/>

</bean>

<bean class="com.imooc.spring.ioc.class12.Class1" id="class1" parent="parentClass"/>

<property name="attribute4" value="attribute4"/>

<property name="attribute5" value="attribute5"/>

</bean>

<bean class="com.imooc.spring.ioc.class12.Class2" id="class2" parent="parentClass"/>

<property name="attribute7" value="attribute7"/>

<property name="attribute8" value="attribute8"/>

</bean>

运行结果:

https://img1.sycdn.imooc.com//63fa19810001532f14500816.jpg

2、SpringIoc注解

2.1、通过注解来解决繁杂的xml配置

//MyConfiguration.class

@Configuration

public class MyConfiguration {

@Bean(value="bean2")

public Bean1 bean1() {

return new Bean1();

}

}

//Class013Test.class

ApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);

Bean1 bean1 = context.getBean("bean1", Bean1.class);

运行结果:

https://img1.sycdn.imooc.com//63fa198f0001fb4714540816.jpg

2.2、如何简化

https://img1.sycdn.imooc.com//63fa19990001295814460814.jpg

  • component-scan扫描

https://img1.sycdn.imooc.com//63fa19a60001211514460814.jpg

  • @component注解

https://img1.sycdn.imooc.com//63fa19b40001d58414480816.jpg

  • bean别名

https://img1.sycdn.imooc.com//63fa19c00001183814460816.jpg

课程收获:很开心又学到了Bean注入的一种新方式,坚持不断学习,感谢老师。


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消