스프링
Toy클래스 Battery 클래스에 의존 => 주입으로 변경
위에 주석처리 의존상태를 주입하기
package toy;
public class Toy {
// 의존 상태
// private Battery battery = new Battery(10);
private Battery battery;
// DI 방식 : 세터
public void setBattery(Battery battery) {
this.battery = battery;
}
public void move() {
System.out.println("장난감 움직인다.");
battery.changePower();
}
public boolean isBattery() {
return battery.getPower() > 0;
}
}
배터리 클래스는 변경내용 없음
package toy;
public class Battery {
private int power;
// DI방식 : 생성자
public Battery(int power) {
this.power = power;
}
public int getPower() {
return power;
}
public void changePower() {
this.power--;
}
}
@Bean 추가
@Bean
public Battery battery() {
return new Battery(10);
}
@Bean
public Toy toy() {
Toy t = new Toy();
t.setBattery(battery());
return t;
}
실행
package toy;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import config.AppCtx;
public class ToyEx {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppCtx.class);
Toy toy = ctx.getBean("toy", Toy.class);
while (toy.isBattery()) {
toy.move();
}
System.out.println("배터리 부족으로 멈춤.");
}
}
<결과>
7월 21, 2023 6:55:38 오후 org.springframework.context.support.AbstractApplicationContext prepareRefresh
정보: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@27efef64: startup date [Fri Jul 21 18:55:38 KST 2023]; root of context hierarchy
장난감 움직인다.
장난감 움직인다.
장난감 움직인다.
장난감 움직인다.
장난감 움직인다.
장난감 움직인다.
장난감 움직인다.
장난감 움직인다.
장난감 움직인다.
장난감 움직인다.
배터리 부족으로 멈춤.
10번 출력 후 스톱
Swing, 스프링 회원 가입, 비밀번호 변경, list 출력
Win1.java 스윙 전체 코드
package swing;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import config.AppCtx;
import spring.ChangePasswordService;
import spring.DuplicateMemberException;
import spring.MemberListPrinter;
import spring.MemberNotFoundException;
import spring.MemberRegisterService;
import spring.RegisterRequest;
import spring.WrongIdPasswordException;
public class Win1 extends JFrame {
private ApplicationContext ctx =
new AnnotationConfigApplicationContext(AppCtx.class);
private JFrame frame = this;
Win1() {
JButton bt1 = new JButton("new");
JButton bt2 = new JButton("change");
JButton bt3 = new JButton("list");
JButton bt4 = new JButton("info");
JTextArea ta = new JTextArea();
JTextField tf1 = new JTextField();
JTextField tf2 = new JTextField();
JTextField tf3 = new JTextField();
JTextField tf4 = new JTextField();
JLabel lb1 = new JLabel("email");
JLabel lb2 = new JLabel("name");
JLabel lb3 = new JLabel("password");
JLabel lb4 = new JLabel("confirm");
Container c = this.getContentPane();
this.setLayout(null);
this.setTitle("person");
this.setSize(430, 300);
this.setLocation(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
bt1.setSize(70, 30); // 폭과 높이 조절
bt1.setLocation(20, 230); // 위치 조정
c.add(bt1);
bt2.setSize(70, 30); // 폭과 높이 조절
bt2.setLocation(120, 230); // 위치 조정
c.add(bt2);
bt3.setSize(70, 30); // 폭과 높이 조절
bt3.setLocation(220, 230); // 위치 조정
c.add(bt3);
bt4.setSize(70, 30); // 폭과 높이 조절
bt4.setLocation(320, 230); // 위치 조정
c.add(bt4);
tf1.setSize(70, 30); // 폭과 높이 조절
tf1.setLocation(20, 30); // 위치 조정
c.add(tf1);
tf2.setSize(70, 30); // 폭과 높이 조절
tf2.setLocation(120, 30); // 위치 조정
c.add(tf2);
tf3.setSize(70, 30); // 폭과 높이 조절
tf3.setLocation(220, 30); // 위치 조정
c.add(tf3);
tf4.setSize(70, 30); // 폭과 높이 조절
tf4.setLocation(320, 30); // 위치 조정
c.add(tf4);
lb1.setSize(70, 30); // 폭과 높이 조절
lb1.setLocation(20, 5); // 위치 조정
c.add(lb1);
lb2.setSize(70, 30); // 폭과 높이 조절
lb2.setLocation(120, 5); // 위치 조정
c.add(lb2);
lb3.setSize(70, 30); // 폭과 높이 조절
lb3.setLocation(220, 5); // 위치 조정
c.add(lb3);
lb4.setSize(70, 30); // 폭과 높이 조절
lb4.setLocation(320, 5); // 위치 조정
c.add(lb4);
JScrollPane scrollPane = new JScrollPane(ta);
ta.setCaretPosition(ta.getDocument().getLength());
scrollPane.setSize(350, 80);
scrollPane.setLocation(30, 100);
c.add(scrollPane);
this.setVisible(true);
bt1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println("클릭!");
//ta.append("클릭!\n");
// JOptionPane.showMessageDialog(frame, "Welcome to Swing"); // alret 창
// Help 입력 빈 칸인지 확인
if("".equals(tf1.getText())||
"".equals(tf2.getText())||
"".equals(tf3.getText())||
"".equals(tf4.getText())) {
JOptionPane.showMessageDialog
(frame, "명령어 사용법을 확인하세요.\n " + "이메일 이름 암호 암호확인 모두 입력하세요.");
return;
}
MemberRegisterService regSvc =
ctx.getBean("memberRegSvc", MemberRegisterService.class);
RegisterRequest req = new RegisterRequest();
req.setEmail(tf1.getText());
req.setName(tf2.getText());
req.setPassword(tf3.getText());
req.setConfirmPassword(tf4.getText());
if (!req.isPasswordEqualToConfirmPassword()) {
JOptionPane.showMessageDialog(frame, "암호와 확인이 일치하지 않습니다.\n");
return;
}
try {
regSvc.regist(req);
JOptionPane.showMessageDialog(frame, "등록했습니다.\n");
} catch (DuplicateMemberException ed) {
JOptionPane.showMessageDialog(frame, "이미 존재하는 이메일입니다.\n");
}
}
});
bt2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if("".equals(tf1.getText())||
"".equals(tf2.getText())||
"".equals(tf3.getText())||
"".equals(tf4.getText())) {
JOptionPane.showMessageDialog
(frame, "명령어 사용법을 확인하세요.\n " + "이메일 암호 암호확인 모두 입력하세요.");
return;
}
ChangePasswordService changePwdSvc =
ctx.getBean("changePwdSvc", ChangePasswordService.class);
try {
changePwdSvc.changePassword(tf1.getText(), tf3.getText(), tf4.getText());
JOptionPane.showMessageDialog(frame, "암호를 변경했습니다.\n");
} catch (MemberNotFoundException de) {
JOptionPane.showMessageDialog(frame, "존재하지 않는 이메일입니다.\n");
} catch (WrongIdPasswordException de) {
JOptionPane.showMessageDialog(frame, "이메일과 암호가 일치하지 않습니다.\n");
}
}
});
bt3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MemberListPrinter listPrinter =
ctx.getBean("listPrinter", MemberListPrinter.class);
//listPrinter.printAll();
//String str = String.format("%s, %s, %s, %s\n", tf1.getText(),tf2.getText(),tf3.getText(),tf4.getText());
//ta.append(str);
ta.setText(listPrinter.printAllS());
}
});
}
public static void main(String[] args) {
Win1 win = new Win1();
}
}
코드 분석
@Bean 설정정보 가져오기 Appctx클래스를 생성자 파라미터로 전달
private ApplicationContext ctx =
new AnnotationConfigApplicationContext(AppCtx.class);
빈칸 입력 시 명령어 사용법 도움 처리
if("".equals(tf1.getText())||
"".equals(tf2.getText())||
"".equals(tf3.getText())||
"".equals(tf4.getText())) {
JOptionPane.showMessageDialog
(frame, "명령어 사용법을 확인하세요.\n " + "이메일 이름 암호 암호확인 모두 입력하세요.");
return;
}
알럿 띄우기
내부 익명 클래스에서 외부 클래스의 멤버 변수에 접근을 할라면
외부에 private JFrame frame = this; 선언
메시지 대화상자를 현재 프레임에 띄울 수 있게 하기 위해 외부에 선언 후 밑에 처럼 내부 익명클래스에서 사용 가
JOptionPane.showMessageDialog(frame, "띄울 메세지");
입력한 내용 전체 list 출력 하기
package spring;
public class MemberPrinter {
public void print(Member member) {
System.out.printf(
"회원 정보: 아이디=%d, 이메일=%s, 이름=%s, 등록일=%tF\n",
member.getId(), member.getEmail(),
member.getName(), member.getRegisterDateTime());
}
public String printS(Member member) {
return String.format("회원 정보: 아이디=%d, 이메일=%s, 이름=%s, 등록일=%tF\n",
member.getId(), member.getEmail(),
member.getName(), member.getRegisterDateTime());
}
}
위에 print 메서드는 다른 실행문에서 사용하기 때문에 밑에 printS 추가로 메서드 선언
package spring;
import java.util.Collection;
public class MemberListPrinter {
private MemberDao memberDao;
private MemberPrinter printer;
public MemberListPrinter(MemberDao memberDao, MemberPrinter printer) {
this.memberDao = memberDao;
this.printer = printer;
}
public void printAll() {
Collection<Member> members = memberDao.selectAll();
members.forEach(m -> printer.print(m));
// for(Member member : members) {
// printer.print(member);
// }
}
public String printAllS() {
Collection<Member> members = memberDao.selectAll();
String str = "";
for(Member member : members) {
str += printer.printS(member);
}
return str;
}
}
결과
'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정' 카테고리의 다른 글
2023-07-25 48일차 (0) | 2023.07.25 |
---|---|
2023-07-24 47일차 (0) | 2023.07.24 |
2023-07-20 45일차 (0) | 2023.07.20 |
2023-07-19 44일차 (0) | 2023.07.19 |
2023-07-18 43일차 (0) | 2023.07.18 |