SPRING
SPRING发展
最新方法:使用JAVA配置取代XML
最核心的注解:
使用注解配置spring 实现IOC功能
初始User类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| package cn.itcast.springboot.domain;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
public class User {
private String name; private String password;
public User(String name, String password) { this.name = name; this.password = password; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
@Override public String toString() { return "User{" + "name='" + name + '\'' + ", password='" + password + '\'' + '}'; } }
|
Spring Config
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| package cn.itcast.springboot.javaconfig;
import cn.itcast.springboot.dao.UserDao; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration;
@Configuration @ComponentScan(basePackages="cn.itcast.springboot.service")
public class SpringConfig {
@Bean public UserDao getUserDao(){ return new UserDao(); } }
|
UserDao
1 2 3 4 5 6 7 8 9 10 11 12
| package cn.itcast.springboot.dao;
import cn.itcast.springboot.domain.User; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration;
public class UserDao { public User getUser(){ return new User("cailong","123"); } }
|
UserService
1 2 3 4 5 6 7 8 9 10 11
| import org.springframework.stereotype.Service;
@Service public class UserService { @Autowired private UserDao userDao;
public User getUser(){ return this.userDao.getUser(); } }
|
MAIN测试方法
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class); UserService userService=context.getBean(UserService.class); System.out.println(userService.getUser().toString()); context.destroy(); } }
|
pom文件里需要把默认版本改成本地JDK的版本
1
| <properties> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target></properties>
|
测试效果:User{name=’cailong’, password=’123’}
结论:使用JAVA注解代码替代XML能让整个结构更加清晰