在Spring 中想要更简单的存储和读取对象的核心是使用注解,也就是我们接下来要学习Spring 中的相关注解,来存储和读取 Bean对象。
一.存储Bean对象
之前我们存储Bean时,需要在spring-config
中添加一行bean
注册内容才行,如下图所示:
而现在我们只需要一个注解就可以替代之前要写一行配置的尴尬了,不过在开始存储对象之前,我们先要来点准备工作。
1.1 前置工作:配置扫描路径(重要)
注意∶想要将对象成功的存储到Spring 中,我们需要配置一下存储对象的扫描包路径,只有被配置的包下的所有类,添加了注解才能被正确的识别并保存到Spring中。
在spring-config.xml
添加如下配置∶
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:content="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring扫描的根路径(此根路径下的所有spring存对象的注解才能生效)-->
<content:component-scan base-package="这里写自己的包名,如:com.bit">
</content:component-scan>
</beans>
1.2 添加注解存储 Bean对象
想要将对象存储在Spring中,有两种注解类型可以实现:
- 类注解
:@Controller、@Service、@Repository、@Component、@Configuration
。 - 方法注解:
@Bean
.
@Controller(控制器存储)
使用@Controller存储bean的代码如下所示:
import org.springframework.stereotype.Controller;
@Controller //表示将当前的类注册到Spring当中
public class UserController {
/**
* 对象中的测试方法
* @param name
*/
public void sayHi(String name){
System.out.println("Hi,Controller:" +name);
}
}
使用之前读取对象的方式来读取上面的UserController
对象,如下代码所示:
import com.bit.Controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Spring 启动类(为了方便演示Spring的功能而创建)
*/
public class App {
public static void main(String[] args) {
//1.先获取对象的上下文
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
//2.从Spring中获得存入的对象(id默认的规则是将存入的类的首字母小写)
UserController userController = context.getBean("userController",UserController.class);
userController.sayHi("hello");
}
}
@Service(服务存储)
@Service
public class UserService {
public void sayHi(String name)
{
System.out.println("Hi,Service" + name);
}
}
读取 bean 的代码:
import com.bit.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
//1.先获取对象的上下文
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
//得到Service
UserService userService = context.getBean("userService",UserService.class);
userService.sayHi("world");
}
}
@Repository(仓库存储)
使用@Repository存储bean 的代码如下所示:
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository {
public void sayHi(String name){