Spring.Net学习笔记(八)-设置配置文件参数

一、开发环境

VS2013

.netframework4.5

spring.net1.3.1

二、项目结构

image

三、开发过程

1.编写Person类

  1 namespace SpringNetConfigArg
  2 {
  3     public class Person
  4     {
  5         public string UserName { get; set; }
  6     }
  7 }
View Code

2.配置App.config文件

  1 <?xml version="1.0" encoding="utf-8" ?>
  2 <configuration>
  3   <configSections>
  4     <sectionGroup name="spring">
  5       <section name="context" type="Spring.Context.Support.ContextHandler,Spring.Core"/>
  6       <section name="objects" type="Spring.Context.Support.DefaultSectionHandler,Spring.Core"/>
  7     </sectionGroup>
  8     <section name="databaseSettings" type="System.Configuration.NameValueSectionHandler"/>
  9   </configSections>
 10   <!--配置参数-->
 11   <databaseSettings>
 12     <add key="db.datasource" value="."/>
 13     <add key="db.user" value="sa"/>
 14     <add key="db.password" value="123456"/>
 15     <add key="db.database" value="CIS"/>
 16   </databaseSettings>
 17 
 18   <spring>
 19     <context>
 20       <resource uri="config://spring/objects"></resource>
 21     </context>
 22     <objects>
 23       <object type="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer,Spring.Core">
 24         <property name="ConfigSections" value="databaseSettings"></property>
 25       </object>
 26       <!--使用参数-->
 27       <object id="person" type="SpringNetConfigArg.Person,SpringNetConfigArg">
 28         <property name="UserName" value="${db.user}"></property>
 29       </object>
 30     </objects>
 31   </spring>
 32   <startup>
 33     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
 34   </startup>
 35 </configuration>
View Code

3.控制台代码

  1 namespace SpringNetConfigArg
  2 {
  3     class Program
  4     {
  5         static void Main(string[] args)
  6         {
  7             IApplicationContext context = ContextRegistry.GetContext();
  8             Person person = context.GetObject("person") as Person;
  9             Console.WriteLine(person.UserName);
 10 
 11             Console.ReadKey();
 12         }
 13     }
 14 }
View Code
原文地址:https://www.cnblogs.com/kimisme/p/5517084.html