Spring注解方式注入解析

本文介绍如何使用Spring框架中的注解来替代XML配置文件进行依赖注入。通过示例展示了如何利用@Component、@Service、@Autowired等注解实现类的实例化及属性自动装配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说明:使用@Autowired虽然不需要再配置相关参数,但是还是要在配置文件中配置bean,今天我们完全使用注解的方法来实现一下

1.使用注解来在上下文装载bean:(这里不再需要setter方法一样可以运行)

1.@Component(不推荐使用)、@Repository@Service@Controller 只需要在对应的类上加上一个@Component注解,就将该类定义为一个Bean了。

2.使用@Component注解定义的Bean,默认的名称(id)是小写开头的非限定类名。如这里定义的Bean名称就是 userDaoImpl。你也可以指定Bean的名称: @Component("userDao") 

3.@Component是所有受Spring管理组件的通用形式,Spring还提供了更加细化的注解形式:@Repository@Service@Controller,它们分别对应存储层Bean,业务层Bean,和展示层Bean。

@Service
public class AutoWiringService {
    @Autowired
    private AutoWiringDAO autoWiringDAO;

    public void serviceSave(String meString) {
        autoWiringDAO.save(meString);
    }
}
  1. 使用context:component-scan 标签让Bean定义注解工作起来 :
<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <context:component-scan base-package="com.wuyonghu" />

</beans>

3.测试代码:

@Test
    public void testHello5() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        System.out.println(context);
        AutoWiringService bean = (AutoWiringService) context.getBean("autoWiringService");
        bean.serviceSave("吳永鬍");

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值