Java J2EE中的依賴查找

我的見解:設計依賴查找的設計模式,是爲了解耦.java

  • 單一類型依賴查找
    • JNDI javax.naming.Context#lookup
    • JavaBeans java.beans.beancontext.BeanContext
  • 集合類型依賴查找
    • java.beans.beancontext.BeanContext#getCurrentServiceSelectors
  • 層析性依賴查找

Springboot中使用JNDI

JNDI即Java Naming and Directory Interface(JAVA命名和目錄接口),那麼java命名目的就是爲了記錄一些不方便記錄的內容,就像人的名字或DNS中的域名與IP的關係。mysql

兩種模式
  1. Springboot Embedded Tomcat(嵌入Tomcat)使用JNDI
  2. Springboot WAR 使用JNDI

1. Springboot Embedded Tomcat(嵌入Tomcat)使用JNDI

  • 啓用默認禁用的JNDI命名。
  • 構建一個ContextResource對象,而後添加到Context對象中

java:/comp/env/ 固定寫法git

JndiConfig.javagithub

package com.rumenz;

import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.ContextResource;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.jndi.JndiObjectFactoryBean;
import org.springframework.stereotype.Component;
import javax.naming.NamingException;
import javax.sql.DataSource;
@Component
public class JndiConfig {

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcatServletWebServerFactory = new TomcatServletWebServerFactory() {
            @Override
            protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
                tomcat.enableNaming(); //啓用默認禁用的JNDI命名
                return super.getTomcatWebServer(tomcat);

            }
            //數據庫配置信息能夠配置在文件中,數據庫發生變更,只需修改配置文件,而不用修改代碼.
            @Override
            protected void postProcessContext(Context context) {
                ContextResource resource = new ContextResource();
                resource.setName("jdbcMydb");
                resource.setType(DataSource.class.getName());
                resource.setProperty("driverClassName", "com.mysql.jdbc.Driver");
                resource.setProperty("url", "jdbc:mysql://127.0.0.1:3306/test");
                resource.setProperty("username", "root");
                resource.setProperty("password","root1234");
                context.getNamingResources().addResource(resource);
            }
        };
        return tomcatServletWebServerFactory;
    }
    @Bean
    public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
        JndiObjectFactoryBean bean = new JndiObjectFactoryBean();           // create JNDI data source
        bean.setJndiName("java:/comp/env/jdbcMydb");  // jndiDataSource is name of JNDI data source
        bean.setProxyInterface(DataSource.class);
        bean.setLookupOnStartup(true);
        bean.afterPropertiesSet();
        return (DataSource) bean.getObject();
    }

}
複製代碼

MysqlTest.javaweb

package com.rumenz;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

@Component
public class MysqlTest implements ApplicationRunner {
    public static DataSource dataSource = null;

   static {
       Context context = null;
       try {
           context = new InitialContext();
       } catch (NamingException e) {
           e.printStackTrace();
       }
       //根據資源名稱搜索
       try {
           dataSource = (DataSource)context.lookup("java:/comp/env/jdbcMydb");
       } catch (NamingException e) {
           e.printStackTrace();
       }
       System.out.println("static-----");
   }

    public void run(ApplicationArguments args) throws Exception {
        System.out.println("run---------");
        Statement stmt = null;
        try {
            Connection conn = dataSource.getConnection();
            //查詢
            stmt = conn.createStatement();
            String sql = "SELECT id,name FROM qq limit 1";
            ResultSet rs = stmt.executeQuery(sql);
            while(rs.next()){
                int id  = rs.getInt("id");
                String name = rs.getString("name");
                System.out.print("id: " + id);
                System.out.println(", name: " + name);
            }
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
    }
}
複製代碼

源碼:github.com/mifunc/spri…spring

2.Springboot WAR 使用JNDI

打包成war包放到tomcat,須要修改tomcat/conf/context.xml和tomcat/conf/server.xmlsql

tomcat/conf/context.xml數據庫

<ResourceLink name="jdbcMydb" global="jdbcMydb" auth="Container" type="javax.sql.DataSource" />
複製代碼

tomcat/conf/server.xmlapache

<Resource name="jdbcMydb" global="jdbcMydb" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test" username="root" password="root1234" maxActive="100" maxIdle="20" minIdle="5" maxWait="10000"/>
複製代碼

業務代碼設計模式

JNDIController.java

package com.rumenz.controller;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JNDIController {
	@Autowired
	private DataSource dataSource;
	
	@GetMapping("/test")
	public String test() {
		try {
			Connection conn = dataSource.getConnection();
			Statement stmt = conn.createStatement();
			String sql = "SELECT id,name FROM qq limit 1";
			ResultSet rs = stmt.executeQuery(sql);
			while(rs.next()){
				int id  = rs.getInt("id");
				String name = rs.getString("name");
				System.out.print("id: " + id);
				System.out.println(", name: " + name);
			}
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

}

複製代碼

源碼:github.com/mifunc/Spri…

java.beans.beancontext.BeanContext(單一類型依賴查找/集合類型依賴查找)

  • 單一類型依賴查找
    • java.beans.beancontext.BeanContextServicesSupport#getService
  • 集合類型依賴查找
    • java.beans.beancontext.BeanContextServicesSupport#getCurrentServiceSelectors

層析性依賴查找

多個BeanContext相互爲父子關係. 一個service的依賴有可能在多個BeanContext

beancontext.gif

相關文章
相關標籤/搜索