Spring Bean

本文详细介绍了Spring框架中Bean的概念,包括Bean的配置、实例化方式及依赖注入。探讨了XML配置下Bean的定义、作用域及属性设置,并演示了构造方法、静态工厂与实例工厂三种实例化Bean的方法。

Bean:在Spring的应用中,由Spring IoC容器创建,装配和配置应用的组件对象,这里的对象称之为Bean。

一.Bean的配置

<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
   
   <!-- 将指定的类TestDao配置给spring,让spring创建实例 -->
   <bean id="testdao"  class="dao.TestDaoImp"/>
   <!--通过构造方法进行注入  -->
   <bean id="testservice1" class="service.TestServiceImp">
        <!-- 通过构造方法注入对象 -->
        <constructor-arg index="0" ref="testdao"/>
   </bean>
</beans>

二.相关属性及其子元素

id:Bean在BeanFactory中的唯一标识

class:Bean的具体实现类

package test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

import dao.TestDao;

public class Test02 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        BeanFactory beanfac=new XmlBeanFactory(new FileSystemResource("F:\\java_work\\spring01\\src\\applicationContext.xml"));
        //通过容器获取实例
        TestDao testdao=(TestDao) beanfac.getBean("it");
        testdao.sayHello();
	}

}

constructor-arg:使用构造方法注入式,指定构造方法参数

property:bean的子元素,用于设置属性。

scope:Bean实例作用域。

list:<property>元素的子元素,用于封装List或数组类型的依赖注入。

map:<property>元素的子元素,用于封装map类型的依赖注入。

set:<property>元素的子元素,用于封装set类型的依赖注入。

entry:<map>的子元素,用于设置一个键值对。

三.Bean的实例化

Spring实例化Bean有三种方式:构造方法实例化,静态工厂实例化和实例工厂实例化(其中最常用的方法是构造方法实例化)。

1.目录如下

 

(2)创建Beanclass类

package instance;

public class Beanclass {
   public  String Message;
public Beanclass() {
	super();
	
	System.out.println("构造方法实例化!!!");
}
public Beanclass(String message) {
	super();
	Message = message;
	System.out.println(Message);
	
}
   
}

(3)创建静态工厂类——用于创建Beanclass实例

package instance;

public class Beanclass {
   public  String Message;
public Beanclass() {
	super();
	
	System.out.println("构造方法实例化!!!");
}
public Beanclass(String message) {
	super();
	Message = message;
	System.out.println(Message);
	
}
   
}

(4)创建实例工厂类——用于创建Beanclass实例

package instance;

public class instanceBean {
    public  Beanclass createBeanclass() {
    	System.out.println("实例工厂实例化");
    	return new Beanclass();
    }
}

(5)创建配置文件

<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
   <!-- 通过构造函数进行实例化 -->
   <bean id="conbean" class="instance.Beanclass"/>
   <!--通过静态工厂实例化 -->
   <bean id="staticbean" class="instance.StaticBean" factory-method="createbean"></bean>
   
   
   <!--通过实例工厂实例化  -->
   <!-- 配置工厂 -->
   <bean id="myFactory" class="instance.instanceBean"/>
   <!-- 使用factory-bean属性指定配置的工厂吗,使用factory-method属性指定使用工厂中的哪个方法实例化Bean -->
   <bean id="instancebean" factory-bean="myFactory" factory-method="createBeanclass" />
</beans>

(6)创建测试类

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import instance.Beanclass;

public class Test {
    public static void main(String[] args) {
		ApplicationContext appcon=new ClassPathXmlApplicationContext("ApplicationContext.xml");
		//通过构造方法实例化
		Beanclass bean= (Beanclass) appcon.getBean("conbean");
		//通过静态工厂实例化
		Beanclass bean2=(Beanclass) appcon.getBean("staticbean");
		//System.out.println(bean2.Message);
		//通过实例工厂实例化
		Beanclass bean3=(Beanclass) appcon.getBean("instancebean");
	}
}

 

### Spring Boot 中如何定义和使用 Spring Bean #### 1. 使用 `@Component` 注解定义 Bean 可以通过在类上添加 `@Component` 注解来自动注册该类作为 Spring 容器中的一个 Bean。当启动应用时,Spring 的组件扫描机制会发现并加载带有此注解的类。 ```java import org.springframework.stereotype.Component; @Component public class MyService { public void performTask() { System.out.println("Executing task..."); } } ``` 此类会被自动检测到并实例化为名为 `myService` 的 bean[^2]。 #### 2. 配置类中使用 `@Bean` 方法定义 Bean 另一种常见的方式是在配置类里声明静态工厂方法,并在其上方加上 `@Bean` 注解。这种方式可以更灵活地控制 Bean 的创建过程以及初始化参数等。 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public MyRepository myRepository() { return new InMemoryMyRepository(); } private static class InMemoryMyRepository implements MyRepository { /* ... */ } } ``` 这里定义了一个名为 `myRepository` 的bean,它由 `AppConfig.myRepository()` 方法返回的对象表示. #### 3. 处理同名 Bean 覆盖的情况 如果项目中有多个地方尝试定义相同的 Bean 名称,则默认情况下会导致冲突错误。为了支持这种情况下的覆盖操作,可以在 application.properties 文件中设置属性: ```properties spring.main.allow-bean-definition-overriding=true ``` 这使得后来者能够替换掉之前已经存在的相同名字的 Bean 实例[^1].
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值