Spring Without IoC
FuqiangWang
2014年从msn space存档中重新恢复出来!
或许有的时候你并不想用spring的beanFactory,比如,你目前不做j2EE,而是做一般的java应用,并且,项目也已经启动了,并没有使用spring的IoC支持,这种情况下,你是否会怀念spring中提供的种种便利那?!
其实没有了spring的BeanFactory,你同样可以很容易的使用spring的种种便利,不要忘了,spring的BeanFactory组装的也仅仅是普通的pojo而已,现在只是通过一样的方式构造并使用它们就可以了。
比如,我们要在应用中使用spring提供的发送mail的API的支持,那么现在我们现在就可以这样写:
= new JavaMailSenderImpl();
JavaMailSender mailSender ((JavaMailSenderImpl)mailSender).setHost("mail.livedoor.cn");
((JavaMailSenderImpl)mailSender).setUsername("[email protected]");
((JavaMailSenderImpl)mailSender).setPassword("458524033931");
// IF your Mail Server request SMTP authentication, you must set properties below,
// Otherwise, mail sending will fail.
Properties prop = new Properties();
.setProperty("mail.smtp.auth","true");
prop((JavaMailSenderImpl)mailSender).setJavaMailProperties(prop);
.send(new MimeMessagePreparator(){
mailSenderpublic void prepare(MimeMessage message) throws Exception
{
= new MimeMessageHelper(message);
MimeMessageHelper helper .setTo("[email protected]");
helper.setFrom("[email protected]");
helper.setSubject("Spring Mail Test Without IoC");
helper.setText("Spring Mail is cool!");
helper}
});
或者,我们仅仅为了拦截某个对象的方法,而不是很普遍,那么我们也可以这样:
= new BusinessImpl();
BusinessImpl impl = new BusinessBeforeAdvice();
BusinessBeforeAdvice advice // construct advisor in Regexp Way
= new RegexpMethodPointcutAdvisor();
RegexpMethodPointcutAdvisor advisor .setAdvice(advice);
advisor.setPattern(".*doSomething.*");
advisor
= new ProxyFactory();
ProxyFactory factory .setTarget(impl);
factory.addAdvisor(advisor);
factory= (IBusiness)factory.getProxy();
IBusiness bo .doSomething(); bo
怎么样?!是不是很容易那?
仅仅是这几天实在想不出写些什么,故此闲话些许。
「为AI疯狂」星球上,扶墙老师正在和朋友们讨论有趣的AI话题,你要不要⼀起来呀?^-^
这里
- 不但有及时新鲜的AI资讯和深度探讨
- 还分享AI工具、产品方法和商业机会
- 更有体系化精品付费内容等着你,加入星球(https://t.zsxq.com/0dI3ZA0sL) 即可免费领取。(加入之后一定记得看置顶消息呀!)

存量的时代,省钱就是赚钱。
在增量的时代,省钱其实是亏钱。
避坑儿是省钱的一种形式,更是真正聪明人的选择!
弯路虽然也是路,但还是能少走就少走,背后都是高昂的试错成本。
订阅「福报」,少踩坑,少走弯路,多走一步,就是不一样的胜率!
