autowireddecortator.ts
export function Autowired(dependencyid?: string, singleton?: boolean): MyPropDecorator {
return (targetClassPrototype, propertyKey) => {
let ServiceImplInstance: any
let ServiceImplInstanceOrClass = Reflect.getMetadata("ServiceImplInstanceOrClass", targetClassPrototype, propertyKey)
let metaSingleton = Reflect.getMetadata("singleton",
targetClassPrototype, propertyKey)
if (metaSingleton) {//如果是单件模式
ServiceImplInstance = ServiceImplInstanceOrClass
} else {
ServiceImplInstance = new ServiceImplInstanceOrClass();
}
// 改了这里,直接写到class prototype上
targetClassPrototype[`get${propertyKey as string}`] = function() {
return ServiceImplInstance;
}
}
}
UserController.ts
@Controller("/")
class UserController {
@Autowired("userServiceImpl")
@Singleton(true)
private userServiceImpl!: UserServiceInter
@get("/login")
login(req: Request, res: Response): void { xxxx省略 }
@post("/loginprocess")
loginprocess(req: Request, res: Response): void {
let session = getSession(req);
// 从 prototyp 上拿
const UserServiceImpl = UserController.prototype.getuserServiceImpl();
let userinfofrmdb: Userinfo = UserServiceImpl.Login(req.body.username, req.body.pwd)
if (userinfofrmdb && userinfofrmdb.username) { session.userinfofrmdb = userinfofrmdb }
res.setHeader("Content-Type", "text/html;charset=UTF-8")
let outputhtml = "";
if (userinfofrmdb.role === "admin") {
outputhtml += `<div>管理员:${userinfofrmdb.role}</div>`
outputhtml += `<div><a href="/rights">进入管理员权限页面</a></div>`
}
res.write(outputhtml);
res.write(`<div>登录成功,欢迎你:${userinfofrmdb.username}</div>`);
res.write(`<div><a href="/">进入首页</a></div>`);
res.end();
}
// Dummy 接口以便上面调用不报错
private getuserServiceImpl(): UserServiceImpl {
return {} as UserServiceImpl
}
}