Spring-19 Auto-Wiring by type
在Xml文件中定义bean之间的关系时,有3种方法:
1. inner bean
2. 在bean 的property中定义另外一个bean
3. Spring Autowiring(有很多种类型, 这里 by type)
Auto-wiring 的两个问题:
1. When project is very big, it hard to know what exactly happen when use Auto-wiring.
2. beans which are wired should exactly matched. It will exist error casue of ambiguity. For example:
Interface 的 Implement 也可能出现 ambiguity的问题。
package com.caveofprogramming.spring.test;public class Logger { private ConsoleWriter consoleWriter; private FileWriter fileWriter; public void setConsoleWriter(ConsoleWriter consoleWriter) { this.consoleWriter = consoleWriter; } public void setFileWriter(FileWriter fileWriter) { this.fileWriter = fileWriter; } public void writeFile(String text){ fileWriter.write(text); } public void writeConsole(String text){ consoleWriter.write(text); } }
Spring-20 Autowiring by Name
(注意 logger.class与 Spring-19 中的区别 ambiguity)
package com.caveofprogramming.spring.test;public class Logger { private LogWriter consoleWriter; private LogWriter fileWriter; public void setConsoleWriter(LogWriter writer) { this.consoleWriter = writer; } public void setFileWriter(LogWriter fileWriter) { this.fileWriter = fileWriter; } public void writeFile(String text){ fileWriter.write(text); } public void writeConsole(String text){ consoleWriter.write(text); } }
而且,variables 和 bean中的 id 要 match。
Spring-21 Autowiring by Constructor
package com.caveofprogramming.spring.test;public class Logger { private LogWriter consoleWriter; private LogWriter fileWriter; public Logger(ConsoleWriter consoleWriter, FileWriter fileWriter){ this.consoleWriter = consoleWriter; this.fileWriter = fileWriter; } public void setConsoleWriter(LogWriter writer) { this.consoleWriter = writer; } public void setFileWriter(LogWriter fileWriter) { this.fileWriter = fileWriter; } public void writeFile(String text){ fileWriter.write(text); } public void writeConsole(String text){ consoleWriter.write(text); } }
Constructor 是通过Type来match的??
用了autowire=“constructor”后,不能再property??
Spring-22 Default Autowiring
解决Defalult Autowiring 中的byType中的ambiguity
package com.caveofprogramming.spring.test;public class Logger { private ConsoleWriter consoleWriter; private FileWriter fileWriter; /* public Logger(ConsoleWriter consoleWriter, FileWriter fileWriter){ this.consoleWriter = consoleWriter; this.fileWriter = fileWriter; */ public void setConsoleWriter(ConsoleWriter writer) { this.consoleWriter = writer; } public void setFileWriter(FileWriter fileWriter) { this.fileWriter = fileWriter; } public void writeFile(String text){ fileWriter.write(text); } public void writeConsole(String text){ consoleWriter.write(text); } }
Spring-22 Removing Autowire Ambiguities
1. autowire-cadidate="false"
2. primary = "true"