Spring之注解实现依赖注入

1.使用@Autowired注解按类型自动装配引用数据类型

注:自动装配(按类型和名称)基于反射设计创建对象并暴力反射对应属性为私有属性初始化数据,因此无需提供setter方法。自动装配建议使用无参构造方法创建对象,如果不提供对应的构造方法,应提供唯一的构造方法

package domain;

import org.springframework.stereotype.Component;

@Component
public class Animal {
    private String name;
    private Integer age;
}

package domain;

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

@Component
public class People {
    @Autowired
    private Animal animal;

}

package config;

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

@Configuration
@ComponentScan("domain")
public class SpringConfig {
}

import config.SpringConfig;
import domain.People;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Demo {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        People people = ctx.getBean(People.class);
        System.out.println(people);

    }
}

2.使用@Autowired和@Qualifier注解按名称自动装配引用数据类型(不推荐使用)

注:@Qualifier注解无法单独使用,必须配合@Autowired注解使用

package domain;

import org.springframework.stereotype.Component;

@Component("animal")
public class Animal {
    private String name;
    private Integer age;
}

package domain;

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

@Component
public class People {
    @Autowired
    @Qualifier("animal")
    private Animal animal;

}

package config;

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

@Configuration
@ComponentScan("domain")
public class SpringConfig {
}

import config.SpringConfig;
import domain.People;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Demo {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        People people = ctx.getBean(People.class);
        System.out.println(people);

    }
}

3.使用@Value注解实现简单数据类型的注入

package domain;

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

@Component
public class Animal {
    @Value("maomi")
    private String name;
    @Value("123")
    private Integer age;
}
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码届艺术家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值