Spring实践入门3--注解方式IOC/DI

本次需要学习的是使用注解方式完成对象注入的工作
spring使用注解方式完成对象注入有几种方式,下面依次进行介绍及代码演示:


1.applicationContext配置

  <!--注意下面这句-->
   <context:annotation-config/>
   <bean name="car" class="com.cqu.my_spring.Car">
        <property name="brand" value="宝马"></property>
   </bean>
   
   <bean name="person" class="com.cqu.my_spring.Person">
        <property name="name" value="二狗子"></property>
   </bean>

2.@Autowired


注解.PNG

3.测试结果

二狗子
宝马

说明:其中autowired的位置也可以放在set方法前

auto.PNG

我们能不能把Person类,Car类移出applicationContext.xml文件中呢?答案是肯定的。修改后的applicationContext文件如下所示:

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop 
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx 
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context      
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

        <!--只需要加下面这句就好了-->
    <context:component-scan base-package="com.cqu.my_spring"/>
</beans>

其他的如下配置就好了


person.PNG

car.PNG

测试结果依旧是:

二狗子
宝马

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容