0

好的,所以我们正在学习 Spring MVC 3。而且我们对 IoC、DI 等有点陌生。我们想清理很多旧的遗留错误。:-)

我们真的很喜欢@Autowired我们的用户服务等。

然而,我们现在有一个问题,我们想用自动装配来解决。

假设我们有一个Loginbean:

public class Login {
    private String username;
    private String email;

    // getters/setters....
}

这个 bean 应该在会话范围内使用。我们希望每个控制器都能够访问这个单一对象。

我假设我们在 application-config.xml 中需要它

<bean id="login" class="com.example.models.Login" scope="session" />

另外,假设我们有另一个类:

public class Employee {
    private String firstName;
    private String lastName;

    private Login login;

    public Employee(Login paLogin) {
        this.login = paLogin;
    }
}

并把它放在会话中:

<bean id="employee" class="com.example.models.Employee" scope="session" />

好的,稍后在我们的应用程序中,我们有一个电子邮件通知服务。该服务需要从 Login bean 访问username和 以及email来自 Employee bean 的信息。当然,我可以从会话内存访问登录 bean,但这只是一个示例。

@Controller
public class EmailController {

    @Autowired
    Login login;    // this should come from session memory automatically right??

    @Autowired
    Employee employee;    // OK, this should also come from session memory.  Which contains a reference of the login too.  Correct?

    // getters/setters....


    public void sendEmails() {
        // ....
        String email = login.getEmail();
        String firstName = employee.getFirstName();
        // ....
    }
}

我希望这是有道理的。我们真正想要完成的是减少 XML 配置、减少常量参数传递、最少注释等。

任何可以为我指明正确方向的帮助将不胜感激。

谢谢!

4

1 回答 1

2

关于您已安装的控制器的几件事。

@Controller
public class EmailController {

@Autowired
Login login;    // The container has to create a bean of type Login to autowire into EmailController

@Autowired
Employee employee;    //same as above

// getters/setters....
}

如果容器必须在应用程序启动时创建单例 bean,则必须使用注解@Component标记 Login 和 Employee 类。甚至像@Repository、@Service 这样的注解也能做到这一点。您可以查看此答案以了解这些注释之间的区别。

因此,一旦您使用这些注释中的任何一个标记您的类,就会在应用程序启动时创建相应类型的单例 bean。您将在日志中看到类似的内容

Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6c811e18

然后是它创建的 bean 列表。您可以将这些 bean 注入其他 bean。并且这些 bean 不存储在会话中。但它们是由容器本身管理的。

如果您使用@Controller、@Component 等注释,则可以取消 xml bean 定义。您也可以使用 @Configuration 避免大多数 xml 配置文件。您可以在此处此处查看示例。

于 2012-10-23T16:17:22.643 回答