博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用注解装配Bean
阅读量:3936 次
发布时间:2019-05-23

本文共 1447 字,大约阅读时间需要 4 分钟。

 

 注解@Component代表Spring Ioc 会把 这个类扫描生产Bean 实例,而其中 value属性代表这个类在Spring 中的id,这就相当于XML方式定义的Bean  的 id

现在有了这个类还不能测试,因为Spring IOC 并不知道  需要去哪里扫描对象,这时候可以使用一个Java Config 来告诉它

package com.nf147.manage.spring;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Component(value = "role")public class Big {    @Value("1")    private int id;    @Value("可爱的小猪")    private String name;    @Value("1")    private int age;    @Override    public String toString() {        return "Big{" +                "id=" + id +                ", name='" + name + '\'' +                ", age=" + age +                '}';    }}

 

注意:包名要和代码Big类一致,

@ComponentScan 代表 进行扫描,默认是扫描当前包的路径,spring 的包名要和它保持一致才能说扫描,否则是没有的

 

package com.nf147.manage.spring;import org.springframework.context.annotation.ComponentScan;@ComponentScanpublic class PojoConfig {}

 

调用代码:

使用了 AnnotationConfigApplicationContext类去初始化Spring Ioc 容器,它是配置项是Big的PojoConfig类,这样Spring Ioc 就会根据注解的配置去解析对应的资源,来生成容器。

 

 

package com.nf147.manage.spring;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {    public static void main(String[] args) {        ApplicationContext context= new AnnotationConfigApplicationContext(PojoConfig.class);        Big bean = context.getBean(Big.class);        System.out.println(bean);    }}

 

 效果图:

 

 

 
 
 
 
 
 
 
posted @ 2018-12-14 23:13 阅读(...) 评论(...)

转载地址:http://yxhgn.baihongyu.com/

你可能感兴趣的文章
国外程序员整理的系统管理员资源大全 (转)
查看>>
Graylog2+rsyslog+log4j 全过程日志管理环境搭建(转)
查看>>
Elasticsearch6.0 使用Sense发送请求Content-Type报错(转)
查看>>
基于Elasticsearch搜索平台设计(转)
查看>>
用Elasticsearch构建电商搜索平台,一个极有代表性的基础技术架构和算法实践案例(转)
查看>>
使用 Binlog 和 Canal 从 MySQL 抽取数据(转)
查看>>
谈谈对Canal( 增量数据订阅与消费 )的理解(转)
查看>>
Canal数据库同步组件(转)
查看>>
ElasticSearch + Canal 开发千万级的实时搜索系统(转)
查看>>
ElasticSearch + Canal搭建搜索系统(整理中)
查看>>
Centos系统安装MySQL(整理)
查看>>
Ubuntu 下PostgreSQL、postgis安装与配置
查看>>
postgresql计算两点距离(经纬度地理位置)
查看>>
postgres多边形存储--解决 Points of LinearRing do not form a closed linestring
查看>>
postgresql+postgis空间数据库总结
查看>>
spring 之 Http Cache 和 Etag(转)
查看>>
JAVA8-用lamda表达式和增强版Comparator进行排序(转)
查看>>
基于Lucene查询原理分析Elasticsearch的性能(转)
查看>>
依赖多个项目,重复jar包不同版本冲突解决
查看>>
阿里 weex--前端整合开源框架(记录)
查看>>