AdminConnetction.java
package env03;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class AdminConnetction implements InitializingBean, DisposableBean {
private String adminId;
private String adminPw;
private String sub_adminId;
private String sub_adminPw;
public void destroy() throws Exception {
System.out.println("AdminConnection destroy() 소멸자 소멸전 ");
}
public void afterPropertiesSet() throws Exception {
System.out.println("AdminConnection afterPropertiesSet () 생성자 생성이후 ");
}
public String getAdminId() {
return adminId;
}
public void setAdminId(String adminId) {
this.adminId = adminId;
}
public String getAdminPw() {
return adminPw;
}
public void setAdminPw(String adminPw) {
this.adminPw = adminPw;
}
public String getSub_adminId() {
return sub_adminId;
}
public void setSub_adminId(String sub_adminId) {
this.sub_adminId = sub_adminId;
}
public String getSub_adminPw() {
return sub_adminPw;
}
public void setSub_adminPw(String sub_adminPw) {
this.sub_adminPw = sub_adminPw;
}
}
@Bean을 사용하는 클래스에는 반드시 @Configuration 어노테이션을 활용해야함
- @Configuration 안에서 @Bean을 사용해야 싱글톤을 보장받을 수 있으므로 @Bean 어노테이션은 반드시 @Configuration과 함께 사용해주어야 한다
- 1개 이상의 @Bean을 제공하는 클래스의 경우 반드시 @Configuration을 명시해 주어야 싱글톤이 보장됨
PropertySourcesPlaceholderConfigurer
Properties 파일값읽기 (@Value로 읽어 들이기)
- 메소드에 static 을 선언한다. (지정하지 않으면 @Value("${.....}") 사용시 null 발생
- java 에서 사용시 @Value("${database.url}" String dbUrl; 과 같이 사용한다.
ApplicationConfig.java
package env03;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
@Configuration
public class ApplicationConfig {
//2properties에 있는 값이 들어감
@Value("${admin.id}")
private String adminId;
@Value("${admin.pw}")
private String adminPw;
@Value("${sub_admin.id}")
private String sub_adminId;
@Value("${sub_admin.pw}")
private String sub_adminPw;
@Bean //1환경작업에 의해 값이 들어옴
public static PropertySourcesPlaceholderConfigurer Properties() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
System.out.println("2.Properties Run..");
Resource[] locations = new Resource[2]; // 배열 2개로 잡음
locations[0] = new ClassPathResource("admin3.properties");
locations[1] = new ClassPathResource("sub_admin3.properties");
configurer.setLocations(locations);
return configurer;
}
@Bean //3 set을 이용해 값을 넣어줌
public AdminConnetction adminConfig() {
AdminConnetction adminConnetction = new AdminConnetction();
System.out.println("3. adminConfig Run");
adminConnetction.setAdminId(adminId);
adminConnetction.setAdminPw(adminPw);
adminConnetction.setSub_adminId(sub_adminId);
adminConnetction.setSub_adminPw(sub_adminPw);
return adminConnetction;
}
}
EnvMainClass03.java
package env03;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import env02.AdminConnection;
public class EnvMainClass03 {
public static void main(String[] args) {
System.out.println("1. EnvMainClass03 Run ... ");
//anotation을 config화 해놓음
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
System.out.println("4 EnvMainClass03 adminConfig Before RUN ");
AdminConnetction connection = ctx.getBean("adminConfig", AdminConnetction.class);
System.out.println("5 EnvMainClass03 adminConfig After RUN ");
System.out.println("connection.getAdminId :" + connection.getAdminId() );
System.out.println("connection.getAdminPw :" + connection.getAdminPw() );
System.out.println("connection.getSub_adminId :" + connection.getSub_adminId() );
System.out.println("connection.getSub_adminPw :" + connection.getSub_adminPw());
}
}
admin3.properties
admin.id=super
admin.pw=12345
sub_admin3.properties
sub_admin.id=sub3
sub_admin.pw=67890
ServerInfo.java
package env04;
public class ServerInfo {
private String ipNum;
private String portNum;
public String getIpNum() {
return ipNum;
}
public void setIpNum(String ipNum) {
this.ipNum = ipNum;
}
public String getPortNum() {
return portNum;
}
public void setPortNum(String portNum) {
this.portNum = portNum;
}
}
package env04;
import java.util.Scanner;
import org.springframework.context.support.GenericXmlApplicationContext;
public class EnvMainClass04 {
public static void main(String[] args) {
String config = null;
System.out.println("system을 입력하세요? dev OR run");
Scanner scanner = new Scanner(System.in); //스캐너로 입력하기
String str = scanner.next();
if(str.equals("dev")) { //dev면
config = "dev"; //dev 파일 출력
} else if(str.equals("run")) { //run이면
config = "run"; //run 파일 출력
}
scanner.close();
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
//ctx환경작업 //config어떤값을 입력하는지 보고 활성화된다
ctx.getEnvironment().setActiveProfiles(config);
//ctx 를 load화
ctx.load("applicationCTX_dev.xml","applicationCTX_run.xml"); //xml 두개 만들어줌
//ctx 를 refresh해줌
ctx.refresh();
//ServerInfo info 에서 serverInfo.java를 가져와서 작업함
ServerInfo info = ctx.getBean("serverInfo", ServerInfo.class);
//인포 보기 (출력)
System.out.println("ip :" + info.getIpNum());
System.out.println("port :" + info.getPortNum());
ctx.close();
}
}
환경설정으로 위에 마지막 > 안에 profile="dev" 해주기
applicationCTX_dev.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
profile="dev"> <!-- dev 환경설정 해주고 시작 -->
<bean id="serverInfo" class="env04.ServerInfo">
<property name="ipNum" value="Localhost"></property>
<property name="portNum" value="8181"></property>
</bean>
</beans>
환경설정으로 위에 마지막 > 안에 profile="run"해주기
applicationCTX_run.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
profile="run"> <!-- run환경 설정해주고 시작 -->
<bean id="serverInfo" class="env04.ServerInfo">
<property name="ipNum" value="172.30.1.91"></property>
<property name="portNum" value="8080"></property>
</bean>
</beans>
Student.java
package aop1; //핵심관심사 생성
public class Student {
private String name;
private int age;
private int gradeNum;
private int classNum;
public void getStudentInfo() {
System.out.println("이름: " + getName());
System.out.println("나이: " + getAge());
System.out.println("학년: " + getGradeNum());
System.out.println("반: " + getClassNum());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGradeNum() {
return gradeNum;
}
public void setGradeNum(int gradeNum) {
this.gradeNum = gradeNum;
}
public int getClassNum() {
return classNum;
}
public void setClassNum(int classNum) {
this.classNum = classNum;
}
}
package aop1; //핵심관심사 생성
public class Worker {
private String name;
private int age;
private String job;
private void getWorkerInfo() {
System.out.println("이름: " + getName());
System.out.println("나이: " + getAge());
System.out.println("직업: " + getJob());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
LogAop.java
package aop1;
import org.aspectj.lang.ProceedingJoinPoint;
public class LogAop {
// Around Advice에서 사용할 공통기능 메서드는,대부분 파라미터로 전달받은
//ProceedingJoinPoint의 proceed() 메서드만 호출s
public Object loggerAop(ProceedingJoinPoint joinpoint) throws Throwable {
//핵심 관심사 Method
String signatureStr =joinpoint.getSignature().toShortString();
System.out.println(signatureStr + " is start . . . ");
//Returns the current time in milliseconds
long startTime = System.currentTimeMillis();
Object obj;
try {
//핵심관심사 Method 수행
obj = joinpoint.proceed();
return obj;
} finally {
long endTime = System.currentTimeMillis();
System.out.println(signatureStr + " is finished. ");
System.out.println(signatureStr + "경과시간 :" + (endTime - startTime));
}
}
}
AopMainClass01.java
package aop1;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class AopMainClass01 {
public static void main(String[] args) {
AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX01.xml");
Student student = ctx.getBean("student",Student.class );
student.getStudentInfo();
Worker worker = ctx.getBean("worker", Worker.class);
worker.getWorkerInfo();
ctx.close();
}
}
입력순서 aspect -> pointcut -> around
applicationCTX01.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<bean id="LogAop" class="aop1.LogAop"></bean>
<aop:config>
<aop:aspect id="Logger1" ref="LogAop">
<aop:pointcut expression="within(aop1.*)" id="pointcut1" /> <!-- aop1안에 있는 모든것을 실행 -->
<aop:around method="loggerAop" pointcut-ref="pointcut1" /> <!-- pointcut1를 참조해서 loggerAop를 aop:around 방식으로 -->
</aop:aspect>
</aop:config>
<bean id="student" class="aop1.Student">
<property name="name" value="연개소문"></property>
<property name="age" value="50"></property>
<property name="gradeNum" value="3"></property>
<property name="classNum" value="5"></property>
</bean>
<bean id="worker" class="aop1.Worker">
<property name="name" value="이순신"></property>
<property name="age" value="35"></property>
<property name="job" value="개발자"></property>
</bean>
</beans>
.s 하나만 바꿔도 결과값 달라짐 👇❌❌❌👇
within(aop1.) 는 aop1안에 있는 모든것을 실행
within(aop1.s) 해주면 aop1d안에 student만 실행 되어짐
Student.java
package aop2.buz;
public class Student {
private String name;
private int age;
private int gradeNum;
private int classNum;
public Student() {
System.out.println("Student 생성자");
}
public void getStudentInfo() {
System.out.println("이름: " + getName());
System.out.println("나이: " + getAge());
System.out.println("학년: " + getGradeNum());
System.out.println("반: " + getClassNum());
//어쩌다 오류
//System.out.println(10/0);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGradeNum() {
return gradeNum;
}
public void setGradeNum(int gradeNum) {
this.gradeNum = gradeNum;
}
public int getClassNum() {
return classNum;
}
public void setClassNum(int classNum) {
this.classNum = classNum;
}
}
Worker.java
package aop2.buz;
public class Worker {
private String name;
private int age;
private String job;
public void getWorkerInfo() {
System.out.println("이름: " + getName());
System.out.println("나이: " + getAge());
System.out.println("직업: " + getJob());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
LogAop.java
package aop2;
import org.aspectj.lang.ProceedingJoinPoint;
public class LogAop {
public Object loggerAop(ProceedingJoinPoint joinpoint) throws Throwable {
// 핵심업무에 사용 Method
String signatureStr = joinpoint.getSignature().toShortString();
long st = System.currentTimeMillis();
System.out.println(signatureStr + " is start . . . ");
try {
// 핵심업무 수행 aop.buz.Student.getStudentInfo()
Object obj = joinpoint.proceed();
return obj;
} finally {
long et = System.currentTimeMillis();
System.out.println(signatureStr + " is finished. ");
System.out.println(signatureStr + "경과시간 :" + (et - st));
}
}
public void beforeAdvice() {
System.out.println("beforeAdvice");
}
public void afterReturningAdvice() {
System.out.println("afterReturningAdvice");
}
public void afterThrowingAdvice() {
System.out.println("afterThrowingAdvice");
}
public void afterAdvice() {
System.out.println("afterAdvice");
}
}
AopMainClass02.java
package aop2;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import aop2.buz.Student;
import aop2.buz.Worker;
public class AopMainClass02 {
public static void main(String[] args) {
AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX02.xml");
Student student = ctx.getBean("student" ,Student.class );
student.getStudentInfo();
Worker worker = ctx.getBean("worker",Worker.class );
worker.getWorkerInfo();
ctx.close();
}
}
applicationCTX02.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<bean id="logAop" class="aop2.LogAop"> </bean>
<aop:config>
<aop:aspect id="logger" ref="logAop">
<aop:pointcut expression="within(aop2.buz.*)" id="piontcut1"/>
<aop:around method="LoggerAop" pointcut-ref="piontcut1"/>
</aop:aspect>
<aop:aspect id="logger" ref="logAop">
<aop:pointcut expression="within(aop2.buz.*)" id="piontcut2"/>
<aop:before method="beforeAdvice" pointcut-ref="piontcut2"/>
</aop:aspect>
<aop:aspect id="logger" ref="logAop"> <!-- 오류가 발생했을대 실행 -->
<aop:pointcut expression="within(aop2.buz.*)" id="piontcut3"/>
<aop:after-throwing method="afterThrowingAdvice" pointcut-ref="piontcut3"/>
</aop:aspect>
<aop:aspect id="logger" ref="logAop">
<aop:pointcut expression="within(aop2.buz.*)" id="piontcut4"/>
<aop:after method="afterAdvice" pointcut-ref="piontcut4"/>
</aop:aspect>
</aop:config>
<bean id="student" class="aop2.buz.Student">
<property name="name" value="김춘추"></property>
<property name="age" value="10"></property>
<property name="gradeNum" value="3"></property>
<property name="classNum" value="5"></property>
</bean>
<bean id="worker" class="aop2.buz.Worker">
<property name="name" value="김유신"></property>
<property name="age" value="35"></property>
<property name="job" value="개발자"></property>
</bean>
</beans>
package aop3.buz;
public class Student {
private String name;
private int age;
private int gradeNum;
private int classNum;
public void getStudentInfo() {
System.out.println("이름: " + getName());
System.out.println("나이: " + getAge());
System.out.println("학년: " + getGradeNum());
System.out.println("반: " + getClassNum());
}
public void get3StudentInfo() {
System.out.println("이름: " + getName());
System.out.println("나이: " + getAge());
System.out.println("학년: " + getGradeNum());
System.out.println("반: " + getClassNum());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGradeNum() {
return gradeNum;
}
public void setGradeNum(int gradeNum) {
this.gradeNum = gradeNum;
}
public int getClassNum() {
return classNum;
}
public void setClassNum(int classNum) {
this.classNum = classNum;
}
}
package aop3.buz;
public class Worker{
private String name;
private int age;
private String job;
public void getWorkerInfo() {
System.out.println("이름: " + getName());
System.out.println("나이: " + getAge());
System.out.println("직업: " + getJob());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
annotation 방식
LogAop.java
package aop3;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class LogAop {
//.aop3 패키지 안에 있는 모든 메소드
@Pointcut("within(aop3.buz.*)")
private void pointcutMethod() {
}
@Around("pointcutMethod()") //aroud방식으로 연결
public Object loggerAop(ProceedingJoinPoint joinpoint) throws Throwable {
// 핵심업무에 사용 Method
String signatureStr = joinpoint.getSignature().toShortString();
System.out.println(signatureStr + " is start . . . "); //arround방식으로 start
long st = System.currentTimeMillis();
try {
// 핵심업무 수행 aop.buz.Student.getStudentInfo()
Object obj = joinpoint.proceed();
return obj;
} finally {
long et = System.currentTimeMillis();
System.out.println(signatureStr + " is finished. ");
System.out.println(signatureStr + "경과시간 :" + (et - st));
}
}
@Before("within(aop3.buz.*)") //@Before방식으로 연결
public void beforeAdvice() {
System.out.println("beforeAdvice");
}
@After("within(aop3.buz.*)") // @After방식으로 연결
public void afterAdvice() {
System.out.println("afterAdvice");
}
}
xml 방식
AopMainClass03.java
package aop3;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import aop3.buz.Student;
public class AopMainClass3 {
public static void main(String[] args) {
AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX03.xml");
Student student = ctx.getBean("student" ,Student.class );
student.getStudentInfo();
student.getStudentInfo();
student.get3StudentInfo();
ctx.close();
}
}
혼합 방식
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<!-- annotation방식을 쓸때 연결해줌 -->
<aop:aspectj-autoproxy/>
<bean id="logAop" class="aop3.logAop"></bean>
<bean id="student" class="aop3.buz.Student">
<property name="name" value="홍길동"></property>
<property name="age" value="10"></property>
<property name="gradeNum" value="3"></property>
<property name="classNum" value="5"></property>
</bean>
</beans>
package ch05;
//설계도 //설계도는 main메소드 필요 없음 .
public class Car {
String color; // Member 변수, 필드
int speed;
public Car (){
}
public Car (String color, int speed){
this.color = color; //this는 나의 변수에 있는 값
this.speed = speed;
}
// void = 메소드
void speedUp() { //위에 class에 있는 변수를 보여지게 하는것
speed ++;
System.out.println(speed+"속도를 올렸다.");
}
void speedDown() {
speed --;
System.out.println(speed+"속도를 내렸다.");
}
void print() {
System.out.println("색깔:" + color);
System.out.println("속도:" + speed);
}
}
package ch05;
public class CarEx { //car 설계도 실행클레스
//설계도 실행시킬려면 main 메소드 존재
public static void main(String[] args) {
//선언 메모리 생성
Car myCar = new Car(); //new car이라는 이름을 불러서 Car 설계도에서 호출
myCar.color = "빨강"; //.찍으면 설계도 호출가능
myCar.speed = 200;
myCar.speedUp();
myCar.print();
//1.선언
Car yourCar;
yourCar = new Car(); //생성 //처음에 new car 라고 생성자 만들어주기**
yourCar.color = "초록";
yourCar.speed = 150;
yourCar.print();
yourCar.speedUp();
}
}
주차정산 설계도 실습
package ch05;
//설계도
public class Car3 { //메소드 정의
String name; // 차 이름
int inTime;// 입고시간
int outTime; // 출고시간
int fee; // 주차요금
//상수 final (마지막값, 변경할수 없는값)
final int AMTPERTIME = 3000; //AMTPERTIME 반드시 대문자로 쓰기
//시간당 요금
//생성자--> constructor //생성자의 역활 - 1.메모리 만들어줌 2.나의 맴버 변수값에 기본 값 세팅
Car3(String n, int in, int out) { //-----------------------------------메소드에 값을 넣어줌
name = n;
inTime = in;
outTime = out;
}
void print() { //--------------------메소드 값을 사람들에게 보여줌 프린트 .
int fee = (outTime-inTime)*AMTPERTIME;
System.out.println("차 이름"+name);
System.out.println("입고시간"+inTime);
System.out.println("출고시간"+outTime);
System.out.println("주차요금"+fee);
System.out.println("--------------");
}
}
package ch05;
public class Car3Ex {
public static void main(String[] args) {
// TODO Auto-generated method stub
Car3 c1 = new Car3("소나타", 10, 14);
Car3 c2 = new Car3("그랜저", 9, 20);
Car3 c3 = new Car3("아반떼", 12, 13);
//final
//c1.AMTPERTIME = 2500;
c1.print();
c2.print();
c3.print();
}
}