在xml 定义的 bean,然后 用 注解来修改 bean 的作用域是不起效果的,例子如下:
application-context.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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:property-placeholder/>
<bean id="helloService" class="sample.xml.service.HelloWorldService"/>
<bean id="application" class="sample.xml.SampleSpringXmlApplication"/>
</beans>
HelloWorldService .java
package sample.xml.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")// 这里是不起作用的
public class HelloWorldService {
private int count = 0;
HelloWorldService(){
System.out.println("constructing");
}
public String getHelloMessage() {
return "Hello "+ count++;
}
}
main 入口
package sample.xml;
import java.util.Collections;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import sample.xml.service.HelloWorldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
public class SampleSpringXmlApplication implements CommandLineRunner {
private static final String CONTEXT_XML = "classpath:/META-INF/application-context.xml";
@Autowired
ApplicationContext applicationContext;
@Override
public void run(String... args) {
HelloWorldService helloWorldService = applicationContext.getBean(HelloWorldService.class);
System.out.println( helloWorldService.getHelloMessage() );
HelloWorldService helloWorldService2 = applicationContext.getBean(HelloWorldService.class);
System.out.println( helloWorldService2.getHelloMessage() );
}
public static void main(String[] args) throws Exception {
SpringApplication application = new SpringApplication();
application.setSources(Collections.singleton(CONTEXT_XML));
application.run(args);
}
}
输出
一大坨输出blabla......
constructing // 只有一个初始化
2018-04-13 12:25:23.798 INFO 10464 --- [ main] sample.xml.SampleSpringXmlApplication : Started SampleSpringXmlApplication in 0.688 seconds (JVM running for 1.228)
Hello 0
Hello 1
2018-04-13 12:25:23.820 INFO 10464 --- [ Thread-0] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6e9a5ed8: startup date [Fri Apr 13 12:25:23 CST 2018]; root of context hierarchy