用@Component注解代替@Configuration注解,定义bean
1 package com.timo.entity; 2 3 import org.springframework.beans.factory.annotation.Value; 4 import org.springframework.stereotype.Repository; 5 import org.springframework.stereotype.Service; 6 7 /** 8 * 这里可以写@Component,@Service,@Controller注解,写@Repository注解会报错 9 * 报错的原因是在配置文件或者注解排除了@Repository. 10 */ 11 @Service 12 public class Dog { 13 // @Value("pug") 14 private String name; 15 // @Value("18") 16 private Integer age; 17 18 public String getName() { 19 return name; 20 } 21 22 public void setName(String name) { 23 this.name = name; 24 } 25 26 public Integer getAge() { 27 return age; 28 } 29 30 public void setAge(Integer age) { 31 this.age = age; 32 } 33 }
1 package com.timo.entity; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Component; 5 6 @Component 7 public class Master { 8 @Autowired 9 private Dog dog; 10 private String name; 11 12 public String getName() { 13 return name; 14 } 15 16 public Master(String name) { 17 this.name = name; 18 } 19 20 public void setName(String name) { 21 this.name = name; 22 } 23 24 public Dog getDog() { 25 return dog; 26 } 27 28 public void setDog(Dog dog) { 29 this.dog = dog; 30 } 31 public void showDogInfo(){ 32 System.out.println("name="+dog.getName()); 33 System.out.println("age="+dog.getAge()); 34 } 35 }
package com.timo.entity; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; @Component public class FactoryMethodComponent { @Bean @Scope("prototype") public static Dog dog(){ Dog dog = new Dog(); dog.setAge(20); dog.setName("人民"); return dog; } @Bean public static Master master(){ Master master = new Master("ouyangfeng"); master.setDog(dog()); return master; } public void doWork(){ System.out.println("I can do everything"); } }
测试类的代码如下:
package com.timo.test2; import com.timo.entity.Dog; import com.timo.entity.FactoryMethodComponent; import com.timo.entity.Master; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Test5 { public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(FactoryMethodComponent.class); Dog dog = applicationContext.getBean(Dog.class); System.out.println("name="+dog.getName()); System.out.println("age="+dog.getAge()); System.out.println("***********************"); FactoryMethodComponent factoryMethodComponent = applicationContext.getBean(FactoryMethodComponent.class); factoryMethodComponent.doWork(); Master master = applicationContext.getBean(Master.class); System.out.println("master "+master.getDog().getName()); } }