三、Spring中的Java配置类

作者: 数独题 | 来源:发表于2017-03-04 10:04 被阅读432次

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配置类,代码如下:

<?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"
    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" >
    <context:annotation-config/>
    <!-- 加载Java配置类 -->
    <bean class="inter.AppConfig"/>
</beans>

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

@Configuration
@ImportResource("classpath:/beans.xml")
public class AppConfig()
{
    .............
}

相关文章

网友评论

    本文标题:三、Spring中的Java配置类

    本文链接:https://www.haomeiwen.com/subject/aymlgttx.html