Spring Boot Autowired
Annotation
Name | Note |
---|---|
@Component | Register Spring DI |
@Service | Almost all same as @Component, but it is Business Logic. It should be used in Service |
@Autowirted | Inject bean automatically |
Component in Service
com.atmarkplant.SptringTest.bean.ExampleDAO.java
public interface ExampleDAO { public String find(); }
This is just interface
com.atmarkplant.SptringTest.bean.ExampleDAOImpl
@Component public class ExampleDAOImpl implements ExampleDAO { @Override public String find() { return "Test"; } }
This is actual implementation for ExampleDAO.
This class has @Component
com.atamrkplant.SpringTest.controller
@Service public class TestServiceImpl implements TestService { @Autowired private ExampleDAO exampleServoce; @Override public ServiceBean getBean() { exampleServoce.find(); // In ServiceBean bean = new ServiceBean(); bean.setId(1); bean.setName("Tiger"); return bean; } @Override public ServiceBean createBean(Integer id, String name) { ServiceBean bean = new ServiceBean(); bean.setId(id); bean.setName(name); return bean; } }
Service in Controller
com.atmarkplant.SpringTest.bean.ServiceBean
@Data public class ServiceBean { private Integer id; private String name; }
com.atmarkplant.SpringTest.controller.TestService
@Service public interface TestService { public ServiceBean getBean(); public ServiceBean createBean(Integer id, String name); }
This is Service interface.
com.atmarkplant.SpringTest.controller.TestServiceImpl
@Service public class TestServiceImpl implements TestService { @Autowired private ExampleDAO exampleServoce; @Override public ServiceBean getBean() { exampleServoce.find(); ServiceBean bean = new ServiceBean(); bean.setId(1); bean.setName("Tiger"); return bean; } @Override public ServiceBean createBean(Integer id, String name) { ServiceBean bean = new ServiceBean(); bean.setId(id); bean.setName(name); return bean; } }
Use this service in controller
com.atmarkplant.SpringTest.controller.TestController
@RestController public class TestController { @Autowired TestService testService; @RequestMapping("/test") @ResponseBody public String getTest() { ServiceBean bean = testService.getBean(); return bean.getName(); } }
So far, Service and its Interface and Controller are same package.
Ref
@Autowiredと@Serviceアノテーションで、Dependency Injectionしてみる。