在Spring中,手動注入Bean可以通過以下幾種方式實現:
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
@Service
public class MyService {
@Autowired
private MyBean myBean;
}
<bean id="myBean" class="com.example.MyBean" />
<bean id="myService" class="com.example.MyService">
<property name="myBean" ref="myBean" />
</bean>
@Component
public class MyBean {
// ...
}
@Service
public class MyService {
@Autowired
private MyBean myBean;
}
@Service
public class MyService {
@Autowired
private MyBean myBean;
}
無論使用哪種方式,Spring都會在啟動時自動掃描和處理Bean的注入。