Spring註釋版工程demo

Spring註釋版工程demo

使用註解配置spring工程,最簡單的spring demo。

config類

package demo.mq;

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


@Configuration
@ComponentScan
public class SpringConfig {

    public static void main(String[] args) {
        ApplicationContext appCtx = new AnnotationConfigApplicationContext(SpringConfig.class);
        MqConsumer mc = (MqConsumer)appCtx.getBean("mqConsumer");
        mc.sayHi();
        System.out.println("appCtx init ok");
    }
}

bean

main函數可以寫在配置類中,也可以單獨類中實現。ComponentScanComponent標籤是對應的,掃描Component標籤
初始化操作。
也可以直接使用Bean標籤替代Component標籤,在SpringConfig添加初始化函數。

@Bean
public MqConsumer mqConsumer() {
    return new MqConsumer();
}
package demo.mq;

import org.springframework.stereotype.Component;

@Component
public class MqConsumer {
    public MqConsumer() {
        System.out.println("init MqConsumer");
    }

    public void sayHi() {
        System.out.println("Hi ");
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章