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获得,然后注入。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值