spring配置bean的细节二

本文介绍了Spring框架中内部Bean的使用方式及其局限性,并详细阐述了如何通过继承配置实现Bean属性的重用与覆盖,包括配置示例及运行结果。
一 内部bean
<bean id="foo" class="....Foo">
    <property name=”属性”>
    <!—第一方法引用-->
    <ref bean='bean对象名'/>
    <!—内部bean-->
    <bean>
    <properyt></property>
</bean>
</property>
</bean>
这种方式的缺点是你无法在其它地方重用这个bar实例,原因是它是专门为foo而用。

二 继承配置
1、继承
2、继承配置
3、覆盖父 Bean配置
4、可以设置 <bean> 的abstract 属性为 true, Spring 不会实例化该Bean

三 代码
1 Student
package com.hsp.inherit;
public class Student {
        
        protected String name;
        protected int age;
        public String getName() {
                return name;
        }
        public void setName(String name) {
                this.name = name;
        }
        public int getAge() {
                return age;
        }
        public void setAge(int age) {
                this.age = age;
        }
}

2 Gradate
package com.hsp.inherit;
public class Gradate extends Student {
        private String degree;
        public String getDegree() {
                return degree;
        }
        public void setDegree(String degree) {
                this.degree = degree;
        }
        
}

3 beans.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:context="http://www.springframework.org/schema/context";
                xmlns:tx="http://www.springframework.org/schema/tx";
                xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd";>
<!-- 配置一个学生对象 -->
<bean id="student" class="com.hsp.inherit.Student">
        <property name="name" value="顺平" />
        <property name="age" value="30"/>
</bean>
<!-- 配置Grdate对象 -->
<bean id="grdate" parent="student" class="com.hsp.inherit.Gradate">
        <!-- 如果自己配置属性name,age,则会替换从父对象继承的数据  -->
        <property name="name" value="小明"/>
        <property name="degree" value="学士"/>
</bean>
</beans>

4 App1
package com.hsp.inherit;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App1 {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext ac=new ClassPathXmlApplicationContext("com/hsp/inherit/beans.xml");
    
        Gradate gradate=(Gradate) ac.getBean("grdate");
        System.out.println(gradate.getName()+" "+gradate.getAge()+" "+gradate.getDegree());
    }
}

四 测试结果
小明 30 学士
<think>好的,我现在需要回答用户关于Spring配置Bean的不同方式的问题。首先,我得回忆一下Spring框架中配置Bean的几种主要方法。根据用户提供的引用内容,提到了构造方法、静态工厂方法、实例工厂方法,还有使用@Bean注解的方式。另外,可能还有XML配置和注解配置的区别。 首先,用户引用的内容里提到引用[1]中的构造方法、静态工厂和实例工厂方法。引用[2]则提到了@Bean注解的方法。引用[3]是关于XML命名空间的配置,引用[4]涉及初始化和销毁方法。我需要把这些信息整合起来,系统地列出不同的配置方式,并给出示例。 可能需要分几个部分来讲解:XML配置、注解配置、Java配置类等。每种方式的具体步骤和示例代码。比如在XML中使用<bean>标签,通过构造方法实例化;静态工厂需要指定factory-method,实例工厂则需要先配置工厂Bean再调用方法。注解方面,@Component及其衍生注解(@Service, @Repository等)用于类级别的自动扫描,而@Bean通常用在配置类的方法上。Java配置类使用@Configuration和@Bean组合。 另外,还要注意用户提到的初始化方法和销毁方法的顺序,这部分可能需要在每种配置方式中说明如何指定init-method和destroy-method,或者使用注解如@PostConstruct和@PreDestroy。 需要确保每个配置方式都有清晰的示例,比如XML的代码块,Java配置类的代码,以及可能的组件扫描的示例。同时,引用用户提供的参考资料,正确标注引用标记,如[^1]、[^2]等。 可能还需要考虑用户是否了解Spring的基本概念,比如Bean是什么,但根据问题,用户可能已经有一定基础,所以直接进入配置方式的讲解即可。需要结构清晰,分点说明,每种方式给出定义、步骤、示例,并附上引用来源。 最后,生成的相关问题需要与配置Bean的方式相关,可能涉及比较不同方式的优缺点,如何选择,或者更具体的配置细节,如依赖注入、作用域等。但根据用户提供的示例,相关问题应该围绕配置方法本身,比如其他配置方式、配置中的依赖注入处理、配置的最佳实践等。</think>Spring配置 Bean 的常见方式包括 **XML 配置**、**注解配置**和 **Java 配置类**,具体实现方法及示例如下: --- ### 1. **XML 配置** 通过 XML 文件定义 Bean 的元数据,是 Spring 早期的主要配置方式。 #### 构造方法实例化 ```xml <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="userService" class="com.example.UserServiceImpl"/> </beans> ``` - `id` 是 Bean 的唯一标识符,`class` 指定实现类。Spring 会通过默认构造方法实例化 Bean。 #### 静态工厂方法 ```xml <bean id="staticFactoryBean" class="com.example.StaticFactory" factory-method="createInstance"/> ``` - `class` 指向工厂类,`factory-method` 指定静态方法。 #### 实例工厂方法 ```xml <!-- 先定义工厂 Bean --> <bean id="instanceFactory" class="com.example.InstanceFactory"/> <!-- 通过工厂 Bean 创建目标 Bean --> <bean id="targetBean" factory-bean="instanceFactory" factory-method="createTarget"/> ``` - `factory-bean` 引用工厂实例,`factory-method` 指定实例方法。 --- ### 2. **注解配置** 通过注解实现 Bean 的自动扫描和装配,简化配置。 #### 类注解 使用 `@Component` 及其衍生注解(`@Service`, `@Repository`, `@Controller`): ```java @Service public class UserService { // 业务逻辑 } ``` - Spring 自动扫描并实例化该类为 Bean,默认 Bean 名称为类名首字母小写(如 `userService`)。 #### 方法注解(@Bean) 在配置类中使用 `@Bean` 注解定义 Bean: ```java @Configuration public class AppConfig { @Bean public DataSource dataSource() { return new HikariDataSource(); } } ``` - `@Configuration` 标记配置类,`@Bean` 注解的方法返回对象会被注册为 Bean,方法名默认为 Bean 名称。 --- ### 3. **Java 配置类** 结合 `@Configuration` 和 `@Bean` 注解,完全替代 XML 配置: ```java @Configuration @ComponentScan("com.example") public class AppConfig { @Bean public UserRepository userRepository() { return new UserRepositoryImpl(); } @Bean(initMethod = "init", destroyMethod = "cleanup") public UserService userService() { return new UserService(userRepository()); } } ``` - `@ComponentScan` 自动扫描指定包下的组件注解类; - `initMethod` 和 `destroyMethod` 定义初始化和销毁方法[^4]。 --- ### 4. **Bean 生命周期配置** 可通过以下方式控制 Bean 的初始化和销毁顺序: 1. **XML 配置**: ```xml <bean id="exampleBean" class="com.example.ExampleBean" init-method="init" destroy-method="destroy"/> ``` 2. **注解配置**: ```java @PostConstruct public void init() { /* 初始化逻辑 */ } @PreDestroy public void destroy() { /* 销毁逻辑 */ } ``` - 执行顺序:`@PostConstruct` → `InitializingBean.afterPropertiesSet()` → XML 中 `init-method`[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值