spring中Bean对象的执行流程大致分为四步:
①启动Spring容器,在main方法中获取spring上下文对象并配备spring.
- import demo.*;
-
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
-
- public class Test {
- public static void main(String[] args) {
- ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
- }
- }
②实例化Bean对象,spring根据配置文件中的路径搜寻"demo"包中含有注解的类.
通过这些类实例化出Bean对象,并对他们进行初始化Bean对象的属性,
- "1.0" encoding="UTF-8"?>
"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">
-
package="demo">
③将实例化出的Bean对象注册到Spring容器当中.
- @Component
- public class UserBean {
- private String name;
-
- @Bean(name = {"user","wualala"})
- //Bean方法注解,将方法返回的对象存储到spring中变成Bean对象
- public UserBean userBeanMethod(){
- UserBean userBean = new UserBean();
- userBean.name = "wow";
- return userBean;
- }
④Bean对象的使用,将其分配到所需的类中
- @Controller
- public class UserController {
-
- @Resource(name = "user1")
- //@Autowired
- private UserBean userBean;
-
- public UserBean getUserBean() {
- return userBean;
- }
- }
此处的生命周期指的是,Bean对象的创建到销毁的过程.
Bean对象的生命周期主要分成五个主要部分:
1.Bean的实例化
2.设置Bean的属性:
3.Bean初始化
4.使用Bean
5.销毁Bean