Spring中基于Java的@Configuration和@Bean用法是什么

本篇内容主要讲解“Spring中基于Java的@Configuration和@Bean用法是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Spring中基于Java的@Configuration和@Bean用法是什么”吧!

成都创新互联公司是一家集网站建设,安平企业网站建设,安平品牌网站建设,网站定制,安平网站建设报价,网络营销,网络优化,安平网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。

一、首先,需要xml中进行少量的配置来启动Java配置:

二、定义一个配置类

用@Configuration注解该类,等价 与XML中配置beans;用@Bean标注方法等价于XML中配置bean。

代码如下:

package SpringStudy;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import SpringStudy.Model.Counter;import SpringStudy.Model.Piano;@Configurationpublic class SpringConfig {@Beanpublic Piano piano(){return new Piano();}@Bean(name = "counter") public Counter counter(){return new Counter(12,"Shake it Off",piano());}}

三、基础类代码

Counter:

package SpringStudy.Model;public class Counter {public Counter() {}public Counter(double multiplier, String song,Instrument instrument) {this.multiplier = multiplier;this.song = song;this.instrument=instrument;}private double multiplier;private String song;@Resourceprivate Instrument instrument;public double getMultiplier() {return multiplier;}public void setMultiplier(double multiplier) {this.multiplier = multiplier;}public String getSong() {return song;}public void setSong(String song) {this.song = song;}public Instrument getInstrument() {return instrument;}public void setInstrument(Instrument instrument) {this.instrument = instrument;}}

Piano类

package SpringStudy.Model;public class Piano {private String name="Piano";private String sound;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSound() {return sound;}public void setSound(String sound) {this.sound = sound;}}

四、调用测试类

package webMyBatis;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import SpringStudy.Model.Counter;public class SpringTest {public static void main(String[] args) {//ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/bean.xml");// 读取bean.xml中的内容ApplicationContext annotationContext = new AnnotationConfigApplicationContext("SpringStudy");Counter c = annotationContext.getBean("counter", Counter.class);// 创建bean的引用对象System.out.println(c.getMultiplier());System.out.println(c.isEquals());System.out.println(c.getSong());System.out.println(c.getInstrument().getName());}}

注意:如果是在xml中配置beans和bean的话,或者使用自动扫描调用的话,代码为

ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/bean.xml");// 读取bean.xml中的内容Counter c = ctx.getBean("counter", Counter.class);// 创建bean的引用对象

五、运行结果

12.0falseShake it OffPiano---------------------

到此,相信大家对“Spring中基于Java的@Configuration和@Bean用法是什么”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!


文章名称:Spring中基于Java的@Configuration和@Bean用法是什么
URL地址:http://myzitong.com/article/gegeec.html