Saturday, March 19, 2011

Defining contexts in different file

Many a times, we separate beans on the basis of what their behaviour is. Example we separate database beans in one class, service bean in other class. Similar case goes for other types.

Than when using the bean in other file, we have to just import the context file into that class.

Eg. consider the database config file :

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">

<bean id="ds"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>

</beans>


Now suppose the bean uses datasource like this :


 


public class FlightRepository {

private DataSource dataSource;

public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}


So in the config file relating to this bean, we can simply write :


<?xml version="1.0" encoding="UTF-8"?>

<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-3.0.xsd">

<!-- just import the db-config wherever required -->

<import resource="db-config.xml" />

<bean id="flightRepo" class="xml.FlightRepositoryImpl">
<constructor-arg><ref bean="ds" /></constuructor-arg>
</bean>
</beans>


No comments:

Post a Comment

Chitika