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函數可以寫在配置類中,也可以單獨類中實現。ComponentScan
和Component
標籤是對應的,掃描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 ");
}
}