Spring中的Bean的注册有很多种方式,但大多区别不大,首先启动spring这个IOC容器的方式就有两种分别是古老的用*.xml文件来启动还有现在主流用注解式@Configuration声明一个为配置类来启动Spring容器。
首先说明: 得先大概会用Spring和SpringBoot(要不然可能会懵,只是可能会懵而已不用在意),因为SprinBoot里面就都是注解式开发
方式一(不推荐方式): 用xml文件里面的<Bean>标签声明注册 (用*.xml文件启动Spring)
xml文件代码:
<!--采用老式的<bean>标签方式声明注册对象,Person为一个实体类, id为person,
当spring容器启动时就会自己创建这个id=person的对象放到容器中-->
<bean id="person" class="com.entity.Person">
<property name="age" value="18"></property>
<property name="name" value="zhangsan"></property>
</bean>
测试代码:
//方式一: 通过 *.xml 配置文件方式创建,其中bean可以通过<bean>标签创建
//先根据*.xml文件启动spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
//用id获取bean
Person person = (Person) applicationContext.getBean("person");
//输出获取的bean信息
System.out.println(person); //这个Person类重写了toString()方法可以输出对象的信息
控制台输出: 输出了person对象的消息,说明注册成功了
Person{name='zhangsan', age=18}
方式二(不推荐方式,但SSM的话可以继续用): 用xml文件里面的<context:component-scan>包扫描标签声明注册 (还是用*.xml文件启动Spring)
xml文件代码:
<!--采用包扫描注解创建对象,扫描com.entity包下的所有类,这些类只要有
标注了@Controller,@Service,@Repository,@Component等都会被spring容器注册-->
<context:component-scan base-package="com.entity"></context:component-scan>
说明: 我的com.entity包下有3个类是加了@Component或Contorller注解的如下
@Controller
public class ControllerMy{具体代码省略...}
@Component
public class Person{具体代码省略...}
@Component
public class User{具体代码省略...}
测试代码:
//方式二: 通过 *.xml 配置文件方式创建,其中bean可以通过<context:component-scan base-package="*">包扫描创建
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml")