Spring自动装配、以及@Autowired与@Resource注解的使用与区别

上篇文章说过,IOC的注入有两个地方需要提供依赖关系,一个是在类中定义,二是在Spring的XML配置文件中需要去定义(描述)。通过使用自动装配,则省去了第二个依赖关系的定义,减少不必要地重复工作。即我们仅仅需要在类中提供依赖关系,继而把对象交给容器管理就可以完成注入。

我们在实际的程序开发过程中,通过Spring XML描述类之间的依赖关系通常是大篇幅的 ,如果使用自动装配则省去了很多配置,极大地提高了开发效率。并且如果对象地依赖关系发生了更新,我们可以不需要去更新依赖关系地配置。

自动装配有4种方式:

  • no:不使用自动装配
  • byType:根据类型去容器查找并装配
  • byName:根据类名去容器查找并装配
  • default:等价于no,即不使用自动装配

自动装配的指定方式有两种:

  • 全局指定 
  • 局部指定

全局指定:

即在XML的<beans>标签种添加default-autowire,并指定自动装配的方式,此处代码设置为byType。示例代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd"
       default-autowire="byType">
</beans>

​

 byType:根据类型去容器查找并装配 示例代码如下

package com.tyyd.autowire.dao;

public interface IndexDao {
    void test();
}
package com.tyyd.autowire.dao.impl;

import com.tyyd.autowire.dao.IndexDao;

public class IndexDaoImpl implements IndexDao {
    public void test() {
        System.out.println("IndexDao");
    }
}
package com.tyyd.autowire.service;

public interface IndexService {
    void test();
}
package com.tyyd.autowire.service.impl;

import com.tyyd.autowire.dao.IndexDao;
import com.tyyd.autowire.service.IndexService;

public class IndexServiceImpl implements IndexService {

    private IndexDao indexDao;

    public void test() {
        indexDao.test();
    }

    public void setIndexDao(IndexDao indexDao) {
        this.indexDao = indexDao;
    }
}
package com.tyyd.autowire.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ComponentScan("com.tyyd.autowire")
@ImportResource("classpath:spring.xml")
public class JavaConfig {
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd"
       default-autowire="byType">
    <bean id="dao" class="com.tyyd.autowire.dao.impl.IndexDaoImpl"></bean>
    <bean id="indexService" class="com.tyyd.autowire.service.impl.In
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值