Spring Bean的注册

114 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第26天,点击查看活动详情

Snipaste_2022-12-21_19-18-34.jpg 什么是Spring Bean的注册

众所周知,Spring通过IOC容器实现对Bean的集中管理,Bean的初始化可以分为:1.Bean的注册、2.Bean的实例化,在IOC容器中注册后的Bean不一定立刻实例化,Spring Bean的注册主要是指:Spring通过读取配置文件从而获得Bean的各个信息和属性。
什么是Bean的实例化
在一般情况下,我们通过 new+类名()实例化Bean,比如如下代码:

Dog dog= new Dog();

但是在Spring中,Bean的实例化就是指:Spring通过Bean的注册信息对各个Bean实例化的过程。在Spring中Bean的配置文件实例化如以下代码:

<bean name="user2" class="com.pojo.User"/>

下面小编来讲讲如何在Spring中注册Bean
第一种方式:通过xml配置文件的方式注册Bean,ML配置的方式,是Spring最早支持的方式

<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<bean id="student" class="com.pojo.Student"/>
</beans>

第二种方式:使用注解方式 注解方式在Spring2.5开始支持,比如如果我们要注册一个Controller,我们可以使用Spring特定提供的注解 @Controller,如果我们需要定义Service类,我们就要使用Spring给我们提供的@Service,如果我们需要定义自定义的Bean,比如我们写的pojo类,我们可以使用@Component+@ComponentScan(),此括号里面填上我们要注册的POJO的完整的包名。如果我们要注册第三方Bean,比如我们连接数据库时,要给第三方Bean注入数据源,我们可以使用@Bean注解,来注册第三方Bean,如下所示:

@Component
public class User{
}
 
@Service
public class UserServiceImpl{
}
 
@Controller
public class UserController {
}

  @Bean
  public Student student() {
  student.age=22
  student.name="xxx;
  return new Student();
  }