Actframework依赖注入 II - 注入对象类型
发布时间:2020-12-14 01:50:50 所属栏目:百科 来源:网络整理
导读:1. 框架内置绑定 在ActFramework中有大量的服务和组件都可以直接使用依赖注入,其中包括 ActionContext - Encapsulate all data/info relevant to an HTTP request context H.Session - HTTP request session. Also available via actionContext.session() H
1. 框架内置绑定在ActFramework中有大量的服务和组件都可以直接使用依赖注入,其中包括
1.1 应用服务组件
2. Dao目前支持 // Demonstrate inject to field @Controller("user") public class UserService { @javax.inject.Inject private MorphiaDao<User> userDao; @PostAction public void create(User user) { userDao.save(user); } } // Demonstrate inject to parameter @Controller("user") public class UserService { @PostAction public void create(User user,MorphiaDao<User> userDao) { userDao.save(user); } } 如果应用有自定义的Dao,可以直接注入: // The Model @Entity("user") public class User extends MorphiaModel<User> { public String email; ... public static class Dao extends MorphiaDao<User> { public User findByEmail(String email) { return findOneBy("email",email); } } } // The controller @Controller("user") public class UserService { @javax.inject.Inject private User.Dao userDao; @GetAction("{email}") public User findByEmail(String email) { return userDao.findByEmail(email); } } 3. 可构造对象任何拥有public缺省构造函数或者带有 // A class with public default constructor public class Foo { public Foo() {...} } // A class with Inject constructor public class Bar { @javax.inject.Inject public Bar(Foo foo) {...} } 上面的 public class XxxController { @Inject Foo foo; @Inject Bar bar; ... } 注意 可构造对象不能直接用于参数注入 public class XxxController { // foo and bar won't be able to injected throght DI // instead they will be deserialized from form parameters @PostAction("/xxx") public void xxxAction(Foo foo,Bar bar) { } } 但是可以通过 public class YyyController { // this time foo and bar will be injected through DI @PostAction("/yyy") public void xxxAction(@Provided Foo foo,@Provided Bar bar) { } } 4. 应用自定义的绑定假设应用自己定义了接口或抽象类,并且定义了绑定,可以直接使用依赖注入 // The interface public interface MyService { void service(); } // The implemention one public class OneService implements MyService { public void service() {Act.LOGGER.info("ONE is servicing");} } // The implemention two public class TwoService implements MyService { public void service() {Act.LOGGER.info("TWO is servicing");} } // Define bindings public class MyModule extends org.osgl.inject.Module { protected void configure() { bind(MyService.class).to(OneService.class); bind(MyService.class).named("two").to(TwoService.class); } } // Inject the service public class Serviced { @Inject private MyService one; @Inject @Named("two") private MyService two; } 链接
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |