Integrate di with interface programming in Spring
I. Basic DI concepts
Dependency injection (DI) is the basis for implementation of spring containers. It is implemented in the spring-core module. The so-called DI means that the object passively accepts the dependent class rather than actively looking for it. In other words, it means that the object is not the dependent class from the container, instead, when the container instantiates an object, it actively injects the class it depends on to it.
DI role:
Di works with interface programming to reduce the coupling between the layer (web layer) and the business layer.
Ii. Cases of DI with Interface Programming
1. Project
2. Basic Code
PackageCom. cloud. inter;
Public interfaceChangeLetter {
PublicString change ();
}
PackageCom. cloud. inter;
Public classLowerLetterImplementsChangeLetter {
PrivateString str;
PublicString getStr (){
ReturnStr;
}
Public voidSetStr (String str ){
This. Str = str;
}
@ Override
PublicString change (){
//TODOAuto-generated method stub
ReturnStr. toLowerCase ();
}
}
PackageCom. cloud. inter;
Public classUpperLetterImplementsChangeLetter {
PrivateString str;
PublicString getStr (){
ReturnStr;
}
Public voidSetStr (String str ){
This. Str = str;
}
@ Override
PublicString change (){
//TODOAuto-generated method stub
ReturnStr. toUpperCase ();
}
}
3. configuration code
1.0 encoding =UTF-8?>
Http://www.springframework.org/schema/beans
Xmlns: xsi =Http://www.w3.org/2001/XMLSchema-instance
Xmlns: context =Http://www.springframework.org/schema/context
Xmlns: tx =Http://www.springframework.org/schema/tx
Xsi: schemaLocation =Http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd
Http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd
Http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd>
ChangeLetterclass = Com. cloud. inter. LowerLetter>
Str value = ABCDE/>
4. Test code
Package com. cloud. inter;
Importorg. springframework. context. ApplicationContext;
Importorg. springframework. context. support. ClassPathXmlApplicationContext;
Public class App1 {
/**
* @ Param args
*/
Publicstatic void main (String [] args ){
// TODO Auto-generated method stub
ApplicationContextac = new ClassPathXmlApplicationContext (com/cloud/inter/beans. xml );
// Obtain the unused Interface
// UpperLetterchangeLetter = (UpperLetter) ac. getBean (changeLetter );
// System. out. println (changeLetter. change ());
// Use the interface to access the bean
ChangeLetterchangeLetter = (ChangeLetter) ac. getBean (changeLetter );
System. out. println (changeLetter. change ());
}
}