spring java config
맨날 스프링부트로 공부 하다 보니 자바 config가 기억이 잘 안난다.
그래서 대충 한번 해봤다.
일반 스프링과 jpa 구현체는 하이버네이트로 했다.
maven 프로젝트 webapp으로 만들었다.
pom.xml에 다음과 같이 추가를 했다.
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.5.RELEASE</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>1.7.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>1.7.16</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.5</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.191</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.11.Final</version>
<exclusions>
<exclusion>
<groupId>org.jboss.spec.javax.transaction</groupId>
<artifactId>jboss-transaction-api_1.2_spec</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
스프링 컨텍스트랑 webmvc를 추가 하고 로그는 logback을 사용했다.
데이터베이스는 h2 메모리 디비로 일단.
스프링 부트를 안쓰니 디펜더시 설정이 많다.
ROOT 컨텍스트 부터 살펴보자.
@Configuration
@EnableJpaRepositories(basePackages = "me.wonwoo.account")
@EnableTransactionManagement
public class RootConfiguration {
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder
.setType(EmbeddedDatabaseType.H2)
.build();
return db;
}
@Bean
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.createEntityManager();
}
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory() {
LocalContainerEntityManagerFactoryBean containerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
containerEntityManagerFactoryBean.setDataSource(dataSource());
JpaVendorAdapter adaptor = new HibernateJpaVendorAdapter();
containerEntityManagerFactoryBean.setJpaVendorAdapter(adaptor);
containerEntityManagerFactoryBean.setPackagesToScan("me.wonwoo.account");
Properties props = new Properties();
props.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
props.setProperty("hibernate.show_sql", "true");
props.setProperty("hibernate.hbm2ddl.auto", "create");
containerEntityManagerFactoryBean.setJpaProperties(props);
return containerEntityManagerFactoryBean;
}
@Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory);
return jpaTransactionManager;
}
}
dataSource는 h2 메모리 디비를 썼고 하이버네이트 셋팅을 했다. jpa는 처음 설정하는 거라 틀린 거 일지도 모른다.
맨날 boot가 알아서 해주니 (실제 회사에선 개발할때 맨날 mybatis만 써갖고..)
아무튼 이제 webconfig를 보자. 별거 없다.
@Configuration
@EnableWebMvc
@ComponentScan(
basePackages = "me.wonwoo.account"
)
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Bean
@Primary
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
@Autowired
private AccountRepository accountRepository;
@Bean
public InitializingBean initializingBean() {
return () -> {
Arrays.asList(
new Account(1L, "wonwoo"),
new Account(2L, "kevin")
).forEach(accountRepository::save);
};
}
}
ComponentScan 스캔만 하고 api서버를 만들 예정이라 view는 필요 없고 test에 쓰기 위해 ObjectMapper를 빈으로 등록했다.
그리고 초기 데이터를 넣기 위해 InitializingBean을 사용하였다.
설정 마지막으로 디스파처 설정이랑 context를 등록하자. web.xml이라고 생각하면 된다
public class DispatcherServletInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootConfiguration.class);
servletContext.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(MvcConfiguration.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
FilterRegistration.Dynamic filter = servletContext.addFilter("CHARACTER_ENCODING_FILTER", CharacterEncodingFilter.class);
filter.setInitParameter("encoding", "UTF-8");
filter.setInitParameter("forceEncoding", "true");
}
}
context를 등록하고 디스파처를 등록했다.
일단 설정은 이것으로 끝났다.
일반으로 쓰듯이 controller service repository를 만들면 되겠다.
소스는
github 에 올려놨다. 참고만...
테스트 해보니 롤백이 안된다.ㅜㅜㅜㅜㅜㅜㅜㅜ ㅜㅜㅜ
다시 알아봐야 겠다.