随笔 - 227  文章 - 0 评论 - 34 阅读 - 64万

对于java bean的定义和依赖配置,使用xml文件真心是不方便。

今天学习如何用注解,解决bean的定义和注入。

常用注解:

1、自动注入:@Resources,@Autowired

2、Bean定义:@Component、@Repository、@Service 和 @Constroller 

@Component是个泛化概念,可以用在任何层次。如果是web开发,尽量用@Repository、@Service 和 @Constroller

Demo:

以丁磊养猪为例,Pig和DingLei两个类

1、Pig类,以@Component定义为bean

复制代码
@Component
public class Pig {

    private Double weight;
    private String color;
    public Pig(){
        this.weight = 55.8;
        this.color = "black";
    }
    public Double getWeight() {
        return weight;
    }
    public void setWeight(Double weight) {
        this.weight = weight;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String toString(){
        return  weight + " kg " + color + " pig!";
    }
}
View Code
复制代码

2、DingLei类,以@Component定义为bean,同时用@Autowired注入依赖pig

复制代码
@Component
public class DingLei {

    @Autowired
    private Pig pig;
    
    public Pig getPig() {
        return pig;
    }
    public void setPig(Pig pig) {
        this.pig = pig;
    }
    
    public String toString(){
        return "Dinglei has a " + pig.toString();
    }
}
View Code
复制代码

3、bean.xml文件中,配置包扫描,注解才生效

<context:annotation-config/> :启用注释驱动自动注入

<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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context  
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        
       <!-- <context:annotation-config/> -->
       <context:component-scan base-package="anotation"/>
</beans>
View Code
复制代码

4、测试类

复制代码
public class TestAnotation {
    @SuppressWarnings("resource")
    public static void main(String[] arg) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        DingLei dingLei = (DingLei) context.getBean("dingLei");
        System.out.println( dingLei.toString() );        
    }
}
View Code
复制代码

5、运行测试类,可以看到输出。说明注解成功定义bean,并成功完成注入

信息: Loading XML bean definitions from class path resource [bean.xml]
Dinglei has a 55.8 kg black pig!

参考: 

谢谢无私分享的伙伴,写的非常详细的一篇:Spring注解详解

posted on   蛋尼  阅读(25013)  评论(2编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示