依赖注入(dependency injection)
注入ejb: Java代码 [url=][/url]
- @Stateless
- @Remote (Injection.class)
- public class InjectionBean implements Injection {
-
- @EJB (beanName="HelloBean")
- LocalHello helloworld;
-
- public String SayHello() {
- return helloworld.SayHello("注入者");
- }
- }
或: Java代码 [url=][/url]
- @EJB (mappedName = "ESBDaemon/ControlService/local")
- private ControlService cs;
-
- public void contextInitialized(ServletContextEvent sce) {
- cs.init();
- }
注入数据源: Java代码 [url=][/url]
- @Resource(mappedName = "java:/DefaultMySqlDS")
- DataSource myDb;
-
- Connection conn = null;
- try {
- conn = myDb.getConnection();
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery("SELECT studentName FROM student");
- if (rs.next()) str = rs.getString(1); rs.close();
- stmt.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }finally{
- try {
- if(null!=conn && !conn.isClosed()) conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
在jboss中配置数据源 Java代码 [url=][/url]
- <datasources>
- <local-tx-datasource>
- <jndi-name>DefaultMySqlDS</jndi-name>
- ...
- </local-tx-datasource>
- </datasources>
EJB3 的分布式特点
|