asp.net 和spring集成的另一种思路
因项目需要,从Java转.NET,对C#是门外汉![]()
目前asp.net 和 spring.net的集成,需要把要被注入的bean在web.config中配置,相当的不爽,因此准备自制轮子。
实验思路:
鉴于一般把处理业务逻辑的代码从aspx页面单独分离出来成为一个继承自Page的Class,所以可以从这个地方入手,把所有需要注入的bean定义在class文件中,为了提高效率,自定义了InjectAttribute标注需要被注入的Set方法,以下是实验过程:
[AttributeUsage(AttributeTargets.Method)]
public class InjectAttribute : Attribute {
private String beanName;
public InjectAttribute(String beanName) {
this.beanName = beanName;
}
public String BeanName {
get { return this.beanName; }
}
}
实验类:
public class PageInfo {
private String userName;
private String password;
[Inject("balas")]
public void SetUserName(String userName) {
this.userName = userName;
}
[Inject("pwd")]
public void SetPassword(String password) {
this.password = password;
}
public String UserName {
get { return this.userName; }
}
}
实验获取某个类标注有Inject自定义Attribute的方法:
public class Program {
static void Main(string[] args) {
PageInfo page = new PageInfo();
page.SetUserName("keven chen");
Console.WriteLine("Hello World,"+page.UserName);
Type type = page.GetType();
MethodInfo[] methods = type.GetMethods();
for (int i = 0; i < methods.Length; i++) {
Boolean find = false;
foreach (Attribute attr in methods[i].GetCustomAttributes(typeof(InjectAttribute), false)) {
if (attr is InjectAttribute) {
find = true;
Console.WriteLine(((InjectAttribute)attr).BeanName);
break;
}
}
if (find) {
Console.WriteLine(methods[i].Name);
}
}
MethodInfo method = type.GetMethod("SetUserName");
if (null != method) {
method.Invoke(page, new object[] {"bribin"});
}
Console.WriteLine(page.UserName);
}
}
从控制台输出,已经可以正确的获取Inject的方法,下一步就可以根据需要注入的beanName从sping获得,然后注入。