www.91084.com

GVKun编程网logo

Spring简单实用bean配置(spring bean配置)

36

关于Spring简单实用bean配置和springbean配置的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于ConfiguringSpringBeanandcreatingSpringB

关于Spring简单实用bean配置spring bean配置的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Configuring Spring Bean and creating Spring Bea...、java – Spring / LDAP – 在bean配置中调用setter方法、Spring 3.x中三种Bean配置方式比较详解、Spring bean配置基于注解的方式注入等相关知识的信息别忘了在本站进行查找喔。

本文目录一览:

Spring简单实用bean配置(spring bean配置)

Spring简单实用bean配置(spring bean配置)

1.applicationContext.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:p="http://www.springframework.org/schema/p"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
	<!-- 配置bean class:bean的全类名 通过反射的方式在IOC容器中创建bean 所以要求Bean 中必须要有无参数的构造器 -->
	<!-- 通过属性注入方式 比较常用 -->
	<bean id="hello">
		<property name="name" value="huangliusong"></property>
	</bean>


	<!-- 使用构造器注入 -->
	<bean id="car">
		<constructor-arg value="奥迪" type="java.lang.String"></constructor-arg>
		<constructor-arg type="java.lang.String">
			<!-- 如果字面值带特殊符号的值 可以用<![CDATA[]]>包含起来 -->
			<value><![CDATA[<上海>]]></value>
		</constructor-arg>
		<constructor-arg value="1100000" type=""></constructor-arg>
	</bean>


	<!-- <bean id="person"> <property 
		name="name" value="黄柳淞"></property> <property name="age" value="24"></property> 
		指向上面的bean id=car的bean 可以用property的ref属性建立bean之间的引用关系 这是引用外部bean <property 
		name="car" ref="car"></property> </bean> -->
	<bean id="person">
		<property name="name" value="黄柳淞"></property>
		<property name="age" value="24"></property>
		<!-- 内部bean 不能为外部引用 -->
		<property name="car">
			<bean>
				<constructor-arg value="福特"></constructor-arg>
				<constructor-arg value="长安"></constructor-arg>
				<constructor-arg value="20000"></constructor-arg>
			</bean>
		</property>
	</bean>

	<bean id="person2">
		<constructor-arg value="黄柳淞"></constructor-arg>
		<constructor-arg value="23"></constructor-arg>
		<constructor-arg ref="car"></constructor-arg>
		<!-- 为级联属性赋值 -->
		<property name="car.maxSpeed" value="12000"></property>
		<!-- <constructor-arg><null/></constructor-arg> -->
	</bean>



	<!-- 测试如何配置集合属性 -->
	<bean id="person3">
		<property name="name" value="麦克"></property>
		<property name="age" value="22"></property>
		<property name="cars">
			<list>
				<ref bean="car1" />
				<ref bean="car1" />
				<ref bean="car1" />
			</list>
		</property>
	</bean>
	<!-- 使用构造器注入 -->
	<bean id="car1">
		<constructor-arg value="奥迪1" type="java.lang.String"></constructor-arg>
		<constructor-arg type="java.lang.String">
			<!-- 如果字面值带特殊符号的值 可以用<![CDATA[]]>包含起来 -->
			<value><![CDATA[<上海1>]]></value>
		</constructor-arg>
		<constructor-arg value="110000110"></constructor-arg>
	</bean>

	<!-- 配置map集合属性值 -->
	<bean id="person4">
		<property name="name" value="huangliusong"></property>
		<property name="age" value="22"></property>
		<property name="cars">
			<map>
				<entry key="aa" value-ref="car1">
				</entry>
			</map>
		</property>
	</bean>


	<!-- 配置Properties属性值 -->
	<bean id="dataSouece">
		<property name="properties">
			<!-- 使用props和prop为Properties属性赋值 -->
			<props>
				<prop key="user">root</prop>
				<prop key="password">123</prop>
				<prop key="jdbcUrl">jdbc:mysql:///test</prop>
				<prop key="driverClass">com.mysql.jdbc.Driver</prop>
			</props>
		</property>
	</bean>


	<!-- 配置单例的集合bean 以提多个bean进行引用 需要导入util:list命名空间 -->
	<!-- <util:list id="carsss"> <ref bean="car"/> </util:list> <bean id="person5"> <property name="name" 
		value="小五"></property> <property name="age" value="23"></property> <property 
		name="cars" ref="carsss"></property> </bean> -->
	<util:list id="cars">
		<ref bean="car1" />
	</util:list>
	<!-- 通过命名空间对bean的属性进行赋值 需要先导入 p命名空间 -->
	<bean id="person5"p:age="30" p:name="黄柳淞p" p:cars-ref="cars">

	</bean>
	<bean id="person6"> <property name="name" 
		value="小五"></property> <property name="age" value="23"></property> <property 
		name="cars" ref="cars"></property> </bean>
</beans>

2.Person.java

package com.huangliusong.spring.entity;

public class Person {
	private String name;
	private int age;
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Person(String name, int age, Car car) {
		super();
		this.name = name;
		this.age = age;
		this.car = car;
	}
	private Car car;
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", car=" + car
				+ ", getName()=" + getName() + ", getAge()=" + getAge()
				+ ", getCar()=" + getCar() + ", getClass()=" + getClass()
				+ ", hashCode()=" + hashCode() + ", toString()="
				+ super.toString() + "]";
	}
	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;
	}
	public Car getCar() {
		return car;
	}
	public void setCar(Car car) {
		this.car = car;
	}
}

3.Car.java

package com.huangliusong.spring.entity;

public class Car {
	private String brand;
	private String corp;
	private int price;
	public Car(String brand, String corp, int price) {
		super();
		this.brand = brand;
		this.corp = corp;
		this.price = price;
	}
	public Car(String brand, String corp, int price, int maxSpeed) {
		super();
		this.brand = brand;
		this.corp = corp;
		this.price = price;
		this.maxSpeed = maxSpeed;
	}
	public Car() {
	}
	@Override
	public String toString() {
		return "Car [brand=" + brand + ", corp=" + corp + ", price=" + price
				+ ", maxSpeed=" + maxSpeed + ", getBrand()=" + getBrand()
				+ ", getCorp()=" + getCorp() + ", getPrice()=" + getPrice()
				+ ", getMaxSpeed()=" + getMaxSpeed() + ", getClass()="
				+ getClass() + ", hashCode()=" + hashCode() + ", toString()="
				+ super.toString() + "]";
	}
	private int maxSpeed;
	public String getBrand() {
		return brand;
	}
	public void setBrand(String brand) {
		this.brand = brand;
	}
	public String getCorp() {
		return corp;
	}
	public void setCorp(String corp) {
		this.corp = corp;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	public int getMaxSpeed() {
		return maxSpeed;
	}
	public void setMaxSpeed(int maxSpeed) {
		this.maxSpeed = maxSpeed;
	}
}

4.TestSpring.java

package com.huangliusong.spring.test;

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

import com.huangliusong.spring.entity.Car;
import com.huangliusong.spring.entity.HelloWorld;
import com.huangliusong.spring.entity.Person;

public class TestSpring {
	//在没有spring下的普通调用
	@Test
	public void test1() {
		HelloWorld h = new HelloWorld();
		h.setName("huangliusong");
		h.hello();
	}
	/**
	 * 1.创建spring的ioc容器对象
	 * applicationcontext代表IOC容器 该实现类从类路径下加载配置文件
	 */
	@Test
	public void test2(){
		//创建spring的IOC容器对象
		ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
		//2.从IOC容器中获取bean的实例
		HelloWorld helloWorld=(HelloWorld) ctx.getBean("hello");
		//调用hello方法
		helloWorld.hello();
	}
	@Test
	public void test3(){
		ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
		Car car=(Car) ctx.getBean("car");
		System.out.println(car);
	}
	@Test
	public void test4(){
		ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
		Person p=(Person) ctx.getBean("person");
		System.err.println(p);
	}
}

5.TestSpring1.java

package com.huangliusong.spring.test;

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

import com.huangliusong.spring.entity.colection.DataSource;
import com.huangliusong.spring.entity.colection.NewPerson;
import com.huangliusong.spring.entity.colection.Person;


public class TestSpring1 {
	@Test
	public void test1(){
		ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
		Person person=(Person) ctx.getBean("person3");
		System.out.println(person);
	}
	@Test
	public void test2(){
		ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
		NewPerson person=(NewPerson) ctx.getBean("person4");
		System.out.println(person);
	}
	@Test
	public void test3(){
		ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
		DataSource dataSource=(DataSource) ctx.getBean("dataSouece");
		System.out.println(dataSource.getProperties());
	}
	@Test
	public void test4(){
		ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
		Person person=(Person) ctx.getBean("person5");
		System.out.println(person);
	}
	@Test
	public void test5(){
		ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
		Person person=(Person) ctx.getBean("person6");
		System.out.println(person);
	}
	
}

 

Configuring Spring Bean and creating Spring Bea...

Configuring Spring Bean and creating Spring Bea...

This quick start will make you go through the implementations of Spring IoC example and illustrate how to configure your Spring Bean in Spring Configuration file and how to get instance of the bean using Spring IoC container. The example will take a example of Cat class (Cat.java) that will implement Speaks interface (Speaks.java) .

Speaks Interface (Speaks.java)

Speaks interface has only one method.

package com.raistudies.beans;

public interface Speaks {
    public void talk();
}

Cat Class (Cat.java)

Cat class implements Speaks interface and define its own version of talk method.

package com.raistudies.beans;

public class Cat implements Speaks {

    public void talk() {
        System.out.println("Miao-miao");
    }
}

Spring IoC Bean Configuration File to configure Cat class as a Spring Bean

app-config.xml is our Spring Bean Configuration file that configures Cat class as a Spring IoC 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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
		
	<bean id="cat"/>
	
</beans>
  • <beans/>: tag is the top level tag for Spring IoC bean configuration file. This tag contains all the beans configurations.
  • <bean/>: tag is used to configure a class as a bean in Spring IoC container. There are two attributes in it, one is “id”,is used to identify a bean in Spring IoC container and also used to get the instance of the bean from Spring IoC container, and the other one is “class”, which defines the fully qualified java class to be configure as abean.

Runner class (SpringBeanTestRunner.java) of the example

SpringBeanTestRunner class will use Spring IoC to create instance of Cat class and will also invoke talk method in that instance.

package com.raistudies.runner;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.raistudies.beans.Speaks;

public class SpringBeanTestRunner {

    public static void main(String[] args) {
        System.out.println("Initialing bean factory");
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("app-config.xml");
        System.out.println("Getting cat bean instance");
        Speaks speaks = (Speaks)beanFactory.getBean("cat");
        speaks.talk();
    }
}

ClassPathXmlApplicationContext is used to read our Spring IoC bean configuration file “app-config.xml” from class path and configures all beans. BeanFactory is the class that is used as a factory class of all the bean classes in Spring IoC bean configuration file. BeanFactory is also ClassPathXmlApplicationContext in respective to inheritance. Then we use “getBean” method of BeanFactory to get the bean instance by providing bean id as a parameter.

While running the SpringBeanTestRunner class in eclipse you will get following output (the text in red are generated by logger class, you can avoid it):

Spring IoC Bean Creation Example Output

Spring IoC Bean Creation Example Output

You can download full project from bellow links. Import the project in Eclipse ans run SpringBeanTestRunner class to test Spring IoC Bean creation technique.

Source + lib : Download

java – Spring / LDAP – 在bean配置中调用setter方法

java – Spring / LDAP – 在bean配置中调用setter方法

我正在编写 Spring LDAP应用程序,我必须为ContextSource设置身份验证策略.我想在我的bean XML文件中执行此操作. JavaDoc for ContextSource说它有一个名为setter的方法

setAuthenticationStrategy(
    DirContextAuthenticationStrategy authenticationStrategy
)

要从我的beans文件调用此setter,以下XML是否足够?

<bean id="authStrategy">
 ...
</bean>

<bean id="contextSource">

    <property name="url" ... />
    <property name="base" ... />
     ...
    <property name="authenticationStrategy" ref="authStrategy" /> 
</bean>

也就是说,究竟是什么决定了setAuthenticationStrategy方法的调用?是我的属性名称是authenticationStrategy吗? Spring会自动将属性名称转换为适当的setter方法吗?

解决方法

您的怀疑是正确的:Spring将属性名称转换为setter方法.

您用作参数的bean的类型为DefaultTlsDirContextAuthenticationStrategy,并且该方法接受DirContextAuthenticationStrategy类型的对象,因此DefaultTlsDirContextAuthenticationStrategy必须是DirContextAuthenticationStrategy的实现者的子类.

Spring 3.x中三种Bean配置方式比较详解

Spring 3.x中三种Bean配置方式比较详解

以前Java框架基本都采用了XML作为配置文件,但是现在Java框架又不约而同地支持基于Annotation的“零配置”来代替XML配置文件,Struts2、Hibernate、Spring都开始使用Annotation来代替XML配置文件了;而在Spring3.x提供了三种选择,分别是:基于XML的配置、基于注解的配置和基于java类的配置。

下面分别介绍下这三种配置方式;首先定义一个用于举例的JavaBean。

package com.chinalife.dao  
public class LoginUserDao {
	……  
	  // 用于设置初始化方法  
	public void myInit() {
	}
	// 用于设置销毁方法  
	public void myDestroy() {
	}
}

一、 基于XML的配置

<bean id=“loginUserDao” class=“com.chinalife.dao.impl.LoginUserDaoImpl” 
    lazy-init=“true” init-method=“myInit” destroy-method=“myDestroy” 
    scope=“prototype”> 
    ……  
</bean> 

在XML配置中,通过<bean></bean>来定义Bean,通过id或name属性定义Bean的名称,如果未指定id和name属性,Spring则自动将全限定类名作为Bean的名称。通过<property>子元素或者p命名空间的动态属性为Bean注入值。还可以通过<bean>的init-method和destory-method属性指定Bean实现类的方法名来设置生命过程方法(最多指定一个初始化方法和销毁方法)。通过<bean>的scope指定Bean的作用范围。听过<bean>的lazy-init属性指定是否延迟初始化。

当Bean的实现类来源于第三方类库,比如DataSource、HibernateTemplate等,无法在类中标注注解信息,只能通过XML进行配置;而且命名空间的配置,比如aop、context等,也只能采用基于XML的配置。

二、基于注解的配置

@Scope(“prototype”)  
@Lazy(true)  
@Component(“loginUserDao”)  
public class LoginUserDao {  
  ……  
  // 用于设置初始化方法  
  @postconstruct 
  public void myInit() {  
 
  }  
 
  // 用于设置销毁方法  
  @PreDestroy 
  public void myDestroy() {  
  }  
}  

在Bean实现类中通过一些Annotation来标注Bean类:

・@Component:标注一个普通的SpringBean类(可以指定Bean名称,未指定时默认为小写字母开头的类名)

・@Controller:标注一个控制器类

・@Service:标注一个业务逻辑类

・@Repository:标注一个DAO类

通过在成员变量或者方法入参处标注@Autowired按类型匹配注入,也可以使用@Qualifier按名称配置注入。通过在方法上标注@PostConstrut和PreDestroy注解指定的初始化方法和销毁方法(可以定义任意多个)。通过@Scope(“prototype”)指定Bean的作用范围。通过在类定义处标注@Lazy(true)指定Bean的延迟加载。

当Bean的实现类是当前项目开发的,可以直接在java类中使用基于注解的配置,配置比较简单。

三、基于java类配置

@Configuration 
public class Conf {  
  @Scope(“prototype”)  
  @Bean(“loginUserDao”)  
  public LoginUserDao loginUserDao() {  
    return new LoginUserDao();  
  }  
}  

在标注了@Configuration的java类中,通过在类方法标注@Bean定义一个Bean。方法必须提供Bean的实例化逻辑。通过@Bean的name属性可以定义Bean的名称,未指定时默认名称为方法名。在方法处通过@Autowired使方法入参绑定Bean,然后在方法中通过代码进行注入;也可以调用配置类的@Bean方法进行注入。通过@Bean的initMethod或destroyMethod指定一个初始化或者销毁方法。通过Bean方法定义处标注@Scope指定Bean的作用范围。通过在Bean方法定义处标注@Lazy指定Bean的延迟初始化。

当实例化Bean的逻辑比较复杂时,则比较适合基于java类配置的方式。

总结

以上就是本文关于Spring 3.x中三种Bean配置方式比较详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Spring bean配置基于注解的方式注入

Spring bean配置基于注解的方式注入

spring2.5提供了基于注解(Annotation-based)的配置,我们可以通过注解的方式来完成注入依赖。在Java代码中可以使用 @Resource或者@Autowired注解方式来经行注入。虽然@Resource和@Autowired都可以来完成注入依赖,但它们之间是有区 别的。

首先来看一下:

 a) @Resource默认是按照名称来装配注入的,只有当找不到与名称匹配的bean才会按照类型来装配注入;

 b) @Autowired默认是按照类型装配注入的,如果想按照名称来转配注入,则需要结合@Qualifier一起使用;

c) @Resource和@Autowired都可以书写标注在字段或者该字段的setter方法之上

2、使用注解的方式,我们需要修改spring配置文件的头信息,修改部分红色标注,如下

<?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-2.5.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-2.5.xsd">
               
   <context:annotation-config/>
     
</beans>

3、修改以上配置文件的头信息后,我们就可以在Java代码通过注解方式来注入bean,看下面代码

(1)@Resource

public class StudentService3 implements IStudentService {
    // @Resource(name="studentDao")放在此处也是可行的
    private IStudentDao studentDao;

    private String id;

    public void setId(String id) {
        this.id = id;
    }

    @Resource(name = "studentDao")
    // 通过此注解完成从spring配置文件中查找名称为studentDao的bean来装配字段studentDao,
    //如果spring配置文件中不存在
    // studentDao名称的bean则转向按照bean类型经行查找
    public void setStudentDao(IStudentDao studentDao) {
        this.studentDao = studentDao;
    }

    public void saveStudent() {
        studentDao.saveStudent();
        System.out.print(",ID 为:" + id);
    }

}

配置文件添加如下信息

<bean id="studentDao"></bean>
<bean id="studentService3"/>

(2)@Autowired

public class StudentService3 implements IStudentService {
        // @Autowired放在此处也是可行的
        private IStudentDao studentDao;

        private String id;

        public void setId(String id) {
            this.id = id;
        }

        @Autowired
        // 通过此注解完成从spring配置文件中 查找满足studentDao类型的bean
        // @Qualifier("studentDao")则按照名称经行来查找转配的
        public void setStudentDao(IStudentDao studentDao) {
            this.studentDao = studentDao;
        }

        public void saveStudent() {
            studentDao.saveStudent();
            System.out.print(",ID 为:" + id);
        }
    }

配置文件添加如下信息

<bean id="studentDao"></bean>
<bean id="studentService3"/>

注:在java代码中可以使用@Autowire或者@Resource注解方式进行装配,这两个注解的区别是:


@Autowire 默认按照类型装配,默认情况下它要求依赖对象必须存在如果允许为null,可以设置它required属性为false,如果我们想使用按照名称装配,可 以结合@Qualifier注解一起使用;


@Resource默认按照名称装配,当找不到与名称匹配的bean才会按照类型装配,可以通过name属性指定,如果没有指定name属 性,当注解标注在字段上,即默认取字段的名称作为bean名称寻找依赖对象,当注解标注在属性的setter方法上,即默认取属性名作为bean名称寻找 依赖对象.

注意:如果没有指定name属性,并且按照默认的名称仍然找不到依赖的对象时候,会回退到按照类型装配,但一旦指定了name属性,就只能按照名称 装配了.

建议:  @Resource注解是又J2EE提供,而@Autowired是由spring提供,故减少系统对spring的依赖建议使用@Resource的方式;

关于Spring简单实用bean配置spring bean配置的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于Configuring Spring Bean and creating Spring Bea...、java – Spring / LDAP – 在bean配置中调用setter方法、Spring 3.x中三种Bean配置方式比较详解、Spring bean配置基于注解的方式注入的相关知识,请在本站寻找。

本文标签: