1 简介
Java配置是Spring4.x推荐的配置方式,可以完全替代xml配置
Spring的Java配置方式是通过 @Configuration 和 @Bean 这两个注解实现的:
1:@Configuration 作用于类上,相当于一个xml配置文件;
2:@Bean 作用于方法上,相当于xml配置中的<bean>;
项目源码:
https://github.com/3748/SpringBoot.git
2 Spring使用Java配置实例
2.1 工程创建
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springboot</groupId>
<artifactId>springboot-01</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
</dependencies>
</project>
2.2 创建实体类
package com.gp6.springboot01.bean;
public class User {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
2.3 编写UserMapper用于模拟与数据库的交互
package com.gp6.springboot01.mapper;
import com.gp6.springboot01.bean.User;
import java.util.ArrayList;
import java.util.List;
public class UserMapper {
public List<User> queryUserList() {
List<User> result = new ArrayList<User>();
for (int i = 0; i < 10; i++) {
User user = new User();
user.setUsername("username_" + i);
result.add(user);
}
return result;
}
}
2.4 编写UserService 用于实现User数据操作业务逻辑
package com.gp6.springboot01.service;
import com.gp6.springboot01.bean.User;
import com.gp6.springboot01.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> queryUserList() {
return userMapper.queryUserList();
}
}
2.5 编写SpringConfig 用于实例化Spring容器
package com.gp6.springboot01.config;
import com.gp6.springboot01.mapper.UserMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = "com.gp6.springboot01")
public class SpringConfig {
@Bean
public UserMapper getUserMapper(){
return new UserMapper();
}
}
2.6 测试
package com.gp6.springboot01.test;
import com.gp6.springboot01.bean.User;
import com.gp6.springboot01.config.SpringConfig;
import com.gp6.springboot01.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.List;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = context.getBean(UserService.class);
List<User> list = userService.queryUserList();
for (User user : list) {
System.out.println(user.getUsername());
}
context.destroy();
}
}
2.7 项目目录结构