/helloworld4/src/main/resources/config/fuga.properties
beanName=fugaService
/helloworld4/src/main/resources/config/hoge.properties
beanName=hogeService
AbstractExecutableService.java
package com.example.helloworld4.app.welcome;
public abstract class AbstractExecutableService {
public abstract String execute();
}
HogeService.java
package com.example.helloworld4.app.welcome;
import org.springframework.stereotype.Service;
@Service("hogeService")
public class HogeService extends AbstractExecutableService {
@Override
public String execute() {
return "HogeService executed!";
}
}
FugaService.java
package com.example.helloworld4.app.welcome;
import org.springframework.stereotype.Service;
@Service("fugaService")
public class FugaService extends AbstractExecutableService {
@Override
public String execute() {
return "FugaService executed!";
}
}
HelloController.java
package com.example.helloworld4.app.welcome;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
@Controller
public class HelloController {
// AbstractExecutableServiceを継承したBeanのMapをSpringが注入
@Autowired
private Map<String, AbstractExecutableService> serviceMap;
@RequestMapping("/custom-header/{key}")
public ResponseEntity<String> getCustomHeaderResponse(@PathVariable String key) {
System.out.println(key);
try {
ResourceBundle bundle = ResourceBundle.getBundle("config." + key);
String beanName = bundle.getString("beanName");
AbstractExecutableService service = serviceMap.get(beanName);
if (service == null) {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "application/json; UTF-8");
return new ResponseEntity<>("指定されたBeanが見つかりません: " + beanName, headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
String result = service.execute();
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "application/json; UTF-8");
return new ResponseEntity<>("実行結果: " + result, headers, HttpStatus.OK);
} catch (MissingResourceException e) {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "application/json; UTF-8");
return new ResponseEntity<>("プロパティファイルが見つかりません: config/" + key + ".properties", headers, HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "application/json; UTF-8");
return new ResponseEntity<>("エラー: " + e.getMessage(), headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}