Spring. Net learning notes (4)-attributes and constructor injection, spring.net learning notes
I. Development Environment
Operating System: Win10
Compiler: VS2013
. Net version:. net framework4.5
Ii. Assembly
Spring. Core. dll: 1.3.1
Common. Logging. dll
Iii. Development Process 1. Project Structure
Namespace SpringNetDi {public class Product {public string Name {get; set;} public decimal UnitPrice {get; set ;}}}3. Compile ProductFactory. cs
namespace SpringNetDi{ public class ProductFactory { public Product FactoryProduct { get; set; } }}
4. Write Article. cs
Namespace SpringNetDi {public class Article {private string name; private string writer; public Article (string name, string writer) {this. name = name; this. writer = writer;} public void GetMsg () {Console. writeLine ("Hello, I am" + writer );}}}
5. Configure app. config
<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <configSections> <sectionGroup name = "spring"> <section name = "context" type = "Spring. context. support. contextHandler, Spring. core "> </section> <section name =" objects "type =" Spring. context. support. defaultSectionHandler, Spring. core "/> </sectionGroup> </configSections> <spring> <context> <resource uri =" config: // spring/objects "> </resource> </context> <objects> <! -- 01 property injection-value type --> <object name = "product" type = "SpringNetDi. product, springNetDi "> <property name =" Name "value =" marker "> </property> <property name =" UnitPrice "value =" 5 "> </property> </object> <! -- 02 property injection-reference type --> <object name = "factory" type = "SpringNetDi. productFactory, SpringNetDi "> <property name =" FactoryProduct "ref =" product "> </property> </object> <! -- 03 constructor injection --> <object name = "article" type = "SpringNetDi. article, springNetDi "> <constructor-arg name =" name "value =" dependency injection "> </constructor-arg> <constructor-arg name =" writer "value =" Kimisme "> </constructor-arg> </object> </objects> </spring> <startup> <supportedRuntime version = "v4.0" sku = ". NETFramework, Version = v4.5 "/> </startup> </configuration>
6. Console code
namespace SpringNetDi{ class Program { static void Main(string[] args) { IApplicationContext context = ContextRegistry.GetContext(); Product product = context.GetObject("product") as Product; Console.WriteLine(product.Name); ProductFactory factory = context.GetObject("factory") as ProductFactory; Console.WriteLine(factory.FactoryProduct.Name); Article article = context.GetObject("article") as Article; article.GetMsg(); Console.WriteLine("ok"); } }}