java xml 配置_spring用java配置,自动配置代替xml配置。

spring中为了减少xml中配置,可以生命一个配置类(例如SpringConfig)来对bean进行配置。

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

spring中为了减少xml中配置,可以生命一个配置类(例如SpringConfig)来对bean进行配置。

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

;

二.定义一个配置类

用@Configuration注解该类,等价

与XML中配置beans;用@Bean标注方法等价于XML中配置bean。

@Configuration public class SpringConfig { @Bean public Piano

piano(){ return new Piano(); } @Bean(name =

"counter") public

Counter counter(){ return new Counter(12,"Shake it

Off",piano()); } }

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()); }

javaConfig还是没有完全脱离xml配置,而且@Bean 非常麻烦,还需重写构造器,返回具体的值。这时完全可以用

自动转配来代替。通过在配置类中加上@ComponentScan

注解,可以自动进行扫描,而可以完全脱离xml启用组件扫面。当然在每个实现类上@Component注解,就能自动注入到springIoc容器中。

@Configuration

@ComponentScan

public class SpringConfig

{ }

@Component

public

classPiano (){ } @Component(

public

classCounter (){ }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值