package spring.javabase;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import spring.HelloWorld;
@Configuration // 标识配置bean的文件
public class AppConfig {
@Bean // 标记要实例化的对象
public HelloWorld myService() {
return new HelloWorld();
}
}
类似于
<bean id="helloWorld" class="spring.HelloWorld">
<property name="message" value="Hello World!"/>
</bean>
package spring.javabase;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "spring.annotations") //扫描包
public class ScanAppConfig {
}
类似于
<context:component-scan base-package="spring.annotations"></context:component-scan>
测试类
package spring.javabase;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import spring.HelloWorld;
import spring.annotations.controller.UserController;
public class JavaBaseContainer {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class,ScanAppConfig.class);
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World");
helloWorld.getMessage();
UserController controler = (UserController) ctx.getBean("userController");
controler.execute();
}
}