java spring定义类,三、Spring中的Java配置类

本文详细介绍了Spring框架中的Java配置类使用,包括@Configuration、@Bean、@Value等注解的应用,以及如何通过Java配置类加载XML配置。示例展示了如何创建并设置Person和Axe Bean,以及它们之间的依赖关系。
摘要由CSDN通过智能技术生成

Chinese.java

package entity;

import inter.Axe;

import inter.Persion;

public class Chinese implements Persion {

private Axe axe;

private String name;

public void setAxe(Axe axe) {

this.axe = axe;

}

public void setName(String name) {

this.name = name;

}

@Override

public void useAxe() {

// TODO Auto-generated method stub

System.out.println("我是:"+name+axe.chop());

}

}

AppConfig.java

package inter;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import entity.Chinese;

import entity.StoneAxe;

@Configuration

public class AppConfig {

//相当于定义一个名为persionName的变量,其值为Jakee

@Value("Jekee")

String persionName;

@Bean(name="chinese")

public Persion persion()

{

Chinese p=new Chinese();

p.setAxe(null);

p.setName(persionName);

return p;

}

@Bean(name="chinese")

public Axe stoneAxe()

{

return new StoneAxe();

}

}

@Configuration:用于修饰一个Java配置类。

Bean:用于修饰一个方法,该方法的返回值定义成容器中的一个Bean。

Value:用于修饰一个Field,用于为该Field配置一个值,相当于配置一个变量。

Import:用于修饰一个Java配置类,用于向当前Java配置类中导入其他的Java配置类。

Scope:用于修饰一个方法,指定该方法对应的Bean的生命域。

Lazy:用于修饰一个方法,指定该方法对应的Bean是否需要延迟初始化。

DespendsOn:用于修饰一个方法,指定在在初始化对应方法之前初始化指定的Bean。

1、如果以xml配置为主,需要在xml中加载Java配置类,代码如下:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="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

http://www.springframework.org/schema/context/spring-context.xsd" >

2、如果以Java配置类为主,需要在Java配置类中加载xml配置,代码如下:

@Configuration

@ImportResource("classpath:/beans.xml")

public class AppConfig()

{

.............

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值