1、新建Mobile.java与Product.java
Mobile.java:
package com.mrw.springtest4;
public class Mobile {
public void create(){
System.out.println("一部手机正在被创造。。。");
}
}
Product.java:
package com.mrw.springtest4;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Product {
@Bean
public Mobile mobile(){
return new Mobile();
}
}
2、编写Test1.java进行测试
package com.mrw.springtest4;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test1 {
@Test
public void test() {
ApplicationContext context = new AnnotationConfigApplicationContext(Product.class);
Mobile mobile=(Mobile)context.getBean("mobile");
mobile.create();
}
}
3、运行结果为: