728x90
Main
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.example.dto.User;
import com.example.service.DBService;
@SpringBootApplication //서브패키지에 있는 @JavaConfig를 자동생성
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
User user = (User) ctx.getBean("userDTO");
System.out.println(user);
}
}
JavaConfig
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.example.dto.User;
import com.example.service.DBService;
@Configuration
public class JavaConfig {
@Bean(value = "userDTO") //설정 변수: application-properties 설정: 파일 자동 로딩
public User user() {
return new User();
}
}
User(DTO)
package com.example.dto;
import org.springframework.beans.factory.annotation.Value;
public class User {
@Value("${user.username}")
String username;
@Value("${user.age}")
int age;
@Override
public String toString() {
return "user [username=" + username + ", age=" + age + "]";
}
}
Service
package com.example.service;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
//@Service 없음
public class DBService {
public void xxx() { //Configuration에 의해 시작할 때 발동
System.out.println("initMethod.xxx");
}
public void yyy() { //Configuration에 의해 끝날 때 발동
System.out.println("destoryMethod.xxx");
}
public List<String> list() { //Main에서 실행
return Arrays.asList("홍길동", "이순신");
}
@PostConstruct
public void init() {
System.out.println("post init");
}
@PreDestroy
public void dest() {
System.out.println("pre dest");
}
public void destroy() throws Exception{
System.out.println("over dest");
}
public void afterPropertiesSet() throws Exception{
System.out.println("afterPro");
}
}
application.properties
user.username=\uD64D\uAE38\uB3D9
user.age=20
'단순 코드 기록 > Spring Boot' 카테고리의 다른 글
SB_JavaConfig와 Component-Scan (0) | 2024.02.26 |
---|---|
SB_서브 패키지 (0) | 2024.02.26 |
SB_로그 환경 설정 (0) | 2024.02.21 |