2021-11-11

2021-11-11,第1张

2021-11-11 @Autowired注解在集合中的使用
  • 创建com.it.wjn_AnnotionAuto2包
  • 在这个包中创建User类
    public class User {
    String name;
    Integer age;
    String gender;
    public User() {
    super();
    // TODO Auto-generated constructor stub
    }
    public User(String name, Integer age, String gender) {
    super();
    this.name = name;
    this.age = age;
    this.gender = gender;
    }

}

  • 在包中创建basePrint接口
    public interface basePrint {
    void print(User user);
    }
  • 在包中分别创建NamePrint AgePrint GenderPrint类

@Service
public class NamePrint implements basePrint{

@Override
public void print(User user) {
	// TODO Auto-generated method stub
	System.out.println(user.name);
}

}

@Service
public class AgePrint implements basePrint{

@Override
public void print(User user) {
	// TODO Auto-generated method stub
	System.out.println(user.age);
}

}

@Service
public class GenderPrint implements basePrint{

@Override
public void print(User user) {
	// TODO Auto-generated method stub
	System.out.println(user.gender);
}

}

  • 在包中创建print类
    @Service
    public class print {

          @Autowired
         private List  printList;
          
          
          @Autowired
          private Map printMap;
    
             public void PrintList(){
             	       User user = new User("tom", 21, "man");
             	       for (basePrint printService : printList) {
     				   	       printService.print(user);
     				}
             }
          
    
             public void PrintMap(){
             	     User user = new User("jam", 22, "man");
             	    for (String  beanName : printMap.keySet()) {
     					      System.out.println("key值beanName="+beanName);
     					      printMap.get(beanName).print(user);
     				}
             	    
             	       
             }
    

}

  • 在包中创建beans.xml文件
    添加约束

       		
    

7 编写测试类
public class test {
public static void main(String[] args) {
String xmlPath=“com/it/wjn_AnnotionAuto2/beans.xml”;
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(xmlPath);
print bean = (print)classPathXmlApplicationContext.getBean(“print”);

                                     bean.PrintList();
                                     bean.PrintMap();

}

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5437706.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存