spring学习(11):使用配置类

本文介绍了Spring框架中如何使用配置类,通过实例展示了CompactDisc、CDplay、Appconfig类的应用,并给出了程序的运行结果,深入理解配置类在Spring应用中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CompactDisc类

package soundSystem;


import org.springframework.stereotype.Component;

@Component
public class CompactDisc {

    public CompactDisc() {
        super();
        System.out.println("compactdisc无参构造方法");
    }
    public void play(){
        System.out.println("正在播放音乐....");
    }
}

CDplay类

package soundSystem;

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

@Component
public class CDPlayer {
    private CompactDisc cd;

    public CDPlayer() {
        super();
        System.out.println("CDPlayer无参构造方法");
    }
@Autowired
    public CDPlayer(CompactDisc cd) {
        this.cd = cd;
        System.out.println("CDPlayer有参构造方法");
    }

    public void play(){
        cd.play();
    }
}

App类

package soundSystem;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

public class App {
    public static void main(String[] args){
        ApplicationContext context=new AnnotationConfigApplicationContext(App.class);
        CDPlayer player=context.getBean(CDPlayer.class);
        player.play();
    }
}

appconfig类

package soundSystem;

import org.springframework.context.annotation.ComponentScan;
//spring注解类
@ComponentScan
public class Appconfig {
}

运行结果

[INFO ] 2019-10-29 19:11:30,833 method:org.springframework.context.support.AbstractApplicationContext.prepareRefresh(AbstractApplicationContext.java:583)
Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@880ec60: startup date [Tue Oct 29 19:11:30 CST 2019]; root of context hierarchy
[DEBUG] 2019-10-29 19:11:30,857 method:org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221)
Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
[DEBUG] 2019-10-29 19:11:30,857 method:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:449)
Creating instance of bean 'org.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

前端小歌谣

放弃很容易 但是坚持一定很酷

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

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

打赏作者

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

抵扣说明:

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

余额充值