新增程式如下
1.建立一個domain物件
package com.liongogo.domain;
public class SuperHero {
public SuperHero(String id){
this.setId(id);
}
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
2.建立一隻@Configuration
package com.liongogo.configuration;
import com.liongogo.domain.SuperHero;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig {
@Bean("MyBatman")
public SuperHero createBatman(){
return new SuperHero("Batman");
}
@Bean("MyGreenArrow")
public SuperHero createGreenArrow(){
return new SuperHero("GreenArrow");
}
}
3.建立一隻SpringContextUtil用來取得Bean
package com.liongogo.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext context = null;
public SpringContextUtil() {
super();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
public static <T> T getBean(String beanName, Class<T> clazz) {
return context.getBean(beanName, clazz);
}
}
4.取得Bean
package com.liongogo.controller;
import com.liongogo.domain.SuperHero;
import com.liongogo.util.SpringContextUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello() {
SuperHero tGreenArrow = SpringContextUtil.getBean("MyGreenArrow", SuperHero.class);
SuperHero tBatman = SpringContextUtil.getBean("MyBatman", SuperHero.class);
return "Hello "+tGreenArrow.getId()+"、"+tBatman.getId();
}
}
5.執行結果