这是我的代码:
package foo.bar;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
public static void main(String[] args){
AbstractApplicationContext kontekst = new ClassPathXmlApplicationContext("spring.xml");
kontekst.registerShutdownHook();
Shape trojkat = (Shape) kontekst.getBean("Circle");
trojkat.draw();
}
}
Circle.class
package foo.bar;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Component;
@Component
public class Circle implements Shape{
private Point center;
@Override
public void draw() {
System.out.println("Drawin circle");
System.out.println("the point is x:"+center.getX()+", y="+center.getY());
}
public Point getCenter() {
return center;
}
@Resource
public void setCenter(Point center) {
this.center = center;
}
@PostConstruct
public void initalizeCircle(){
System.out.println("init of circle");
}
@PreDestroy
public void destroyCricle(){
System.out.println("destroying circle");
}
}
Spring.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: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">
<context:annotation-config/>
<context:component-scan base-package="foo.bar"/>
<bean id="pointA" class="foo.bar.Point">
<qualifier value="test"/>
<property name="x" value="0"/>
<property name="y" value="0"/>
</bean>
<bean id="pointB" class="foo.bar.Point">
<property name="x" value="60"/>
<property name="y" value="40"/>
</bean>
<bean id="center" class="foo.bar.Point">
<property name="x" value="20"/>
<property name="y" value="30"/>
</bean>
</beans>
我尝试过多种方式,更改源名称。
当我将xml更改为
时<bean id="Circle" class="foo.bar.Circle">
</bean>
Eveyrthing很好,但我想知道为什么,我是Spring的新手。我在stackoverflow上寻找类似的主题,但我无法解决我的问题。
答案 0 :(得分:3)
默认情况下,bean的名称将是以小写字母开头的类的名称。所以,你没有"Circle"
bean,你有一个"circle"
bean。试试这个:
Shape trojkat = (Shape) kontekst.getBean("circle");