@Component、@Autowired、@Resource注解的使用

本文介绍了Spring框架中常用的注解,@Component用于声明Bean,@Autowired实现自动装配,@Resource则提供了指定Bean名称的能力。通过这些注解,开发者可以更加便捷地在Spring容器中管理对象。

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

Spring自从有了注解,就不需要在application.xml中写<bean>组件了。

@component("xxx")表示这是一个Spring Bean,可以直接通过Spring容器创建对象;

@Autowired表示自动注入一个对象;

@Resource和@Autowired差不多。只不过多声名了一个Spring Bean的名称。

package com.zai.pojo;

import org.springframework.stereotype.Component;

@Component("c")
public class Category {
    private int id;
    private String name = "xiao";

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
package com.zai.pojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.DecimalFormat;

@Component("g")
public class Goods {
    private String name;
    private DecimalFormat price;
    @Resource(name = "c")
    private Category category;

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DecimalFormat getPrice() {
        return price;
    }

    public void setPrice(DecimalFormat price) {
        this.price = price;
    }
}

 

package com.zai.test;

import com.zai.pojo.Category;
import com.zai.pojo.Goods;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        Goods goods = (Goods) context.getBean("g");
        System.out.println(goods.getCategory().getName());
    }
}

 

xiao

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值