Configurazione
Mettere il seguente file dentro la cartella resources.
applicationContext.xml
<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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd”
xmlns:util=”http://www.springframework.org/schema/util”>
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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd”
xmlns:util=”http://www.springframework.org/schema/util”>
<context:component-scan base-package=”com” />
<bean id=”provaBean” class=”com.ProvaBean”>
</bean>
</beans>
Bean Spring
creare un file java di nome ProvaBean nel package “com”
ProvaBean.java
package com;
public class ProvaBean {
private String msg = “HelloWord”;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
creare un file java di nome TestBean:
TestBean.java
package com;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestBean {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
“applicationContext.xml”);
ProvaBean obj = (ProvaBean) context.getBean(“provaBean”);
System.out.println(obj.getMsg());
}
}
Esecuzione
lanciare il main del file TestBean. L’ouput sarà: