현재 객체가 다른 객체를 참조하고 있다면 현재 객체는 다른 객체에 대해 의존성을 가짐.

 

Object Dependencies (객체 의존성)

public class PetOwner {
	private AnimalType animal;
    
    public PetOwner() {
    	this.animal = new Dog();
    }
}

PetOwner 객체는 AnimalType 객체(Dog)에 의존한다.

PetOwner 생성자에서 new Dog();를 통해 Dog에 의존성을 가짐

 

문제점

- PetOwner 객체는 AnimalType 객체의 생성을 제어하기 떄문에 두 객체 간에는 긴밀한 결합(tight coupling)이 생기고, tight coupling에 따라 AnimalType 객체를 변경하면 PetOwner객체도 변경됨.

- 하나의 모듈이 바뀌면 의존한 다른 모듈까지 변경되어야 한다

- 두 객체 사이의 의존성이 존재하면 Unit Test 작성이 어려워진다.

 

Dependency Injection (의존성 주입)

= IOC(Inversion of control) 제어의 역전

객체를 직접 생성하는 것이 아니라 외부에서 생성 후 주입

필요의 이유

  1. 의존성 파라미터를 생성자에 작성하지 않아도 되므로 보일러 플레이트 코드를 많이 줄일 수 있습니다. 보일러 플레이트 코드를 줄이는 것만으로도 유연한 프로그래밍이 가능합니다.
  2. Interface에 구현체를 쉽게 교체하면서 상황에 따라 적절한 행동을 정의할 수 있습니다. 이것은 특히 Mock 객체와 실제 객체를 바꿔가며 테스트 할 때 유용합니다.

 

 

벡엔드 담당자와 협업중 자바에서 php서버로 Multipart post를 필요로 하였다.

아래의 클래스를 사용하였으며, 라이브러리는

com.google.guava_1.6.0.jar
0.91MB

구아바?

구아바!

 

 

 

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import com.google.common.base.Strings;
import com.google.common.io.CharStreams;

public class MultipartUploader {

    private static final String CHARSET = "UTF-8";

    private static final String CRLF = "\r\n";

    public String httpUpload(String url, String filename, byte[] byteStream)
        throws MalformedURLException, IOException {

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        final String boundary = Strings.repeat("-", 15) + Long.toHexString(System.currentTimeMillis());

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        OutputStream directOutput = connection.getOutputStream();
        PrintWriter body = new PrintWriter(new OutputStreamWriter(directOutput, CHARSET), true);

        body.append(CRLF);
        addSimpleFormData("가나다라", "atㅋㅋㅋㅇㅇtach1", body, boundary); //텍스트 파라미터
        addSimpleFormData("마바사", "6ㄴㅇㅁ", body, boundary); //텍스트 파라미터
        addFileData("attach", filename, byteStream, body, directOutput, boundary);
        addCloseDelimiter(body, boundary);

        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();
       
        String payload = CharStreams.toString(new InputStreamReader(connection.getInputStream()));
        return payload;
    }
    
    private static void addSimpleFormData(String paramName, String wert, PrintWriter body,
            final String boundary) {

body.append("--").append(boundary).append(CRLF);
body.append("Content-Disposition: form-data; name=\"" + paramName + "\"").append(CRLF);
body.append("Content-Type: text/plain; charset=" + CHARSET).append(CRLF);
body.append(CRLF);
body.append(wert).append(CRLF);
body.flush();
}

private static void addFileData(String paramName, String filename, byte[] byteStream, PrintWriter body,
      OutputStream directOutput, final String boundary) throws IOException {

body.append("--").append(boundary).append(CRLF);
body.append("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + filename + "\"")
.append(CRLF);
body.append("Content-Type: application/octed-stream").append(CRLF);
body.append("Content-Transfer-Encoding: binary").append(CRLF);
body.append(CRLF);
body.flush();

directOutput.write(byteStream);
directOutput.flush();

body.append(CRLF);
body.flush();
}

private static void addCloseDelimiter(PrintWriter body, final String boundary) {
body.append("--").append(boundary).append("--").append(CRLF);
body.flush();
}
    
}

 

위의 파라미터 중 byteStream은 

 

  public static byte[] fileToBinary(File file) {
	    String out = new String();
	    byte[] fileArray = null;
	    FileInputStream fis = null;
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	 
	    try {
	        fis = new FileInputStream(file);
	    } catch (FileNotFoundException e) {
	        System.out.println("Exception position : FileUtil - fileToString(File file)");
	    }
	 
	    int len = 0;
	    byte[] buf = new byte[1024];
	    try {
	        while ((len = fis.read(buf)) != -1) {
	            baos.write(buf, 0, len);
	        }
	 
	          fileArray = baos.toByteArray();
	       // out = new String(base64Enc(fileArray));
	 
	        fis.close();
	        baos.close();
	    } catch (IOException e) {
	        System.out.println("Exception position : FileUtil - fileToString(File file)");
	    }
	 
	    return fileArray;
	}
	 
	public static byte[] base64Enc(byte[] buffer) {
	    return Base64.encodeBase64(buffer);
	}

}

를 사용한다.

fileArray를 리턴하는데 내가 급하게 만든다고 필요없는 메서드가 있긴하다...

 

'프로그래밍 > Java & JSP' 카테고리의 다른 글

Dependency Injection 이란?  (0) 2020.09.12

+ Recent posts