You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

为何使用Spring Bean而非直接初始化对象?

Why Use Spring Beans Instead of Directly Instantiating Objects?

Great question—this is one of the core concepts that trips up many new Spring developers, so let’s break down the key advantages of using Spring’s container-managed beans over plain new instantiation.

Let’s start with your example:

  • Using Spring:
    ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    Account acc = (Account)context.getBean("account");
    acc.printAccName();
    
  • Direct instantiation:
    Account acc2 = new Account();
    acc2.printAccName();
    

At first glance, the direct new looks simpler—but as your application grows, Spring’s approach becomes exponentially more valuable. Here’s why:

1. Dependency Injection & Loose Coupling

Suppose your Account class depends on another component, like an AccountDao to fetch data. With direct instantiation, you’d have to manually create and wire that dependency every time:

AccountDao dao = new AccountDao();
Account acc2 = new Account(dao); // You have to handle this yourself

If AccountDao ever changes (e.g., its constructor adds a new parameter), you’d have to update every single place where you new an Account.

With Spring, you just declare the dependency (via @Autowired or XML configuration), and the container handles the wiring automatically:

public class Account {
    @Autowired
    private AccountDao dao; // Spring injects the pre-configured AccountDao instance

    public void printAccName() {
        // Use dao without manually creating it
    }
}

This makes your classes loosely coupled—you can swap out AccountDao with a mock version for testing, or a different implementation later, without touching the Account class itself.

2. Built-in Lifecycle Management

Spring manages the entire lifecycle of your beans. You can define initialization logic (e.g., connecting to a database) with @PostConstruct, and cleanup logic with @PreDestroy. The container will automatically call these methods at the right time.

With direct new, you’d have to remember to call these methods manually everywhere:

Account acc2 = new Account();
acc2.init(); // Easy to forget!
// ... later ...
acc2.cleanup(); // Even easier to miss in error paths

Spring takes this burden off your plate, especially critical in complex applications with many components.

3. Controlled Instance Scoping

Spring lets you define how many instances of a bean exist (its scope):

  • Singleton (default): One instance shared across the entire application. No need to implement error-prone singleton patterns yourself.
  • Prototype: A new instance every time you request the bean.
  • Request/Session: For web apps, instances tied to an HTTP request or user session.

With direct new, every call creates a new instance—if you want a singleton, you’d have to write the singleton logic (and risk mistakes like thread-safety issues). Spring handles all this with a simple annotation or XML config:

<!-- Singleton (default) -->
<bean id="account" class="com.example.Account"/>

<!-- Prototype -->
<bean id="account" class="com.example.Account" scope="prototype"/>

4. Easy AOP Integration

Aspect-Oriented Programming (AOP) lets you add cross-cutting concerns (like logging, transaction management, or security) to your methods without modifying the actual class code.

For example, if you want to log every call to printAccName(), Spring can create a proxy bean that wraps your Account instance and adds the logging logic automatically. With a direct new instance, you’d have to manually wrap it in a proxy or add the logging code directly to Account—messy and hard to maintain.

5. Centralized Configuration

Spring lets you configure bean properties centrally (via XML, annotations, or Java config). For example, you can set the account name in your spring.xml:

<bean id="account" class="com.example.Account">
    <property name="accName" value="My Savings Account"/>
</bean>

No need to hardcode values in your new calls—change the config, and all instances of Account get the updated value. With direct instantiation, you’d have to modify every new Account("My Savings Account") line and recompile.

When Is Direct Instantiation Okay?

If you’re working on a tiny, throwaway application with no dependencies and no need for lifecycle management, new is fine. But as soon as your app grows beyond a single class, Spring’s beans will save you time, reduce bugs, and make your code far more maintainable.

内容的提问来源于stack exchange,提问作者Rvdrichard

火山引擎 最新活动