标签: spring-ioc

如何在Controller中使用Session Scoped Component

Count.java:

@Component
@Scope(value = "session",proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Count {
    Integer i;
    public Count() {
        this.i = 0;
    }
Run Code Online (Sandbox Code Playgroud)

控制器:

@Controller
public class GreetingController {
    @Autowired private Count count;
    @RequestMapping("/greeting")
    public String greetingForm(Model model) {
        if(count.i == null) i == 0;
        else i++;
        model.addAttribute("count",String.valueOf(count.i));
        return "greeting";
    }
}
Run Code Online (Sandbox Code Playgroud)

但每次我运行这个控制器(/问候语),它甚至在我关闭浏览器时总是增加i,所以如何在Singleton Controller中使用这个Session Scoped Component?

spring dependency-injection spring-mvc spring-ioc spring-boot

4
推荐指数
1
解决办法
5370
查看次数

带有@Bean 注释的 BeanPostProcessor 不起作用

我正在尝试创建一个BeanPostProcessor用于将一些值注册到 Map 的。

BeanPostProcessor,如果我通过创建XML定义bean实例工作正常,但如果我的bean定义更改为@Configuration它不工作。

后处理器

public class InstantiationTracingBeanPostProcessor implements BeanPostProcessor {

  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
      return bean;
  }

  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      System.out.println("Bean '" + beanName );
      return bean;
  }
}
Run Code Online (Sandbox Code Playgroud)

Bean 配置

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;

@org.springframework.context.annotation.Configuration
public class Configuration {
    @Bean
    public @Qualifier("InstantiationTracingBeanPostProcessor")
    InstantiationTracingBeanPostProcessor activitiConfigurationBeanPostProcessor() {
        return new InstantiationTracingBeanPostProcessor();
    }
}
Run Code Online (Sandbox Code Playgroud)

组件扫描配置

<context:component-scan base-package="xyz.config"/>
<context:annotation-config/>
Run Code Online (Sandbox Code Playgroud)

如果我使用上述配置,应用程序就会挂起。但是,如果我使用下面给出的基于 xml 的配置,它就可以正常工作。

<bean class="xyz.bean.InstantiationTracingBeanPostProcessor"/>
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?

spring spring-ioc

3
推荐指数
2
解决办法
9299
查看次数

在运行时更新 bean 属性

我有一个包含一些配置的 bean:

public class CustomerService{
  private Config config;

  @Required
  public void setConfig(Config config){
    this.config = config;
  }
}

public Config {
  private String login;
  private String password;

  //setters/getters
}
Run Code Online (Sandbox Code Playgroud)

应用上下文.xml:

<bean id="config" class="Config"/>
<bean id="customerService" class="CustomerService">
   <property name="config" ref="config"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

并且在运行时获取配置值(通过调用 api)。如何在运行时更新这些值?我可以使用 setter 来做到这一点:

customerService.getConfig().setLogin("login");
Run Code Online (Sandbox Code Playgroud)

java spring spring-ioc

3
推荐指数
1
解决办法
1万
查看次数

Spring注入中的循环依赖 - 这是一个糟糕的设计吗?

我遇到以下问题:

我正在尝试创建bean如下:

@Bean
public abc createABC() {
    return new ABC(--, def(),--);
}
Run Code Online (Sandbox Code Playgroud)

`

@Bean
public DEF def() {
    return new DEF(--, createABC(),--
}
Run Code Online (Sandbox Code Playgroud)

有任何建议可以解决这个问题,而不必考虑基于setter的注入.这是不良设计的指示吗?在我的情况下,这种依赖是必须的.请提供您的观点

java oop spring design-patterns spring-ioc

3
推荐指数
1
解决办法
599
查看次数

使用特定注释注入所有bean

我已经使用Spring几十年了,但之前从未涉及过这个用例.

有没有办法注入所有使用特定注释注释的bean,例如所有带有@Service或者全部的bean @CustomAnnotation

我唯一的想法是注入上下文,获取所有 bean并手动过滤.如果这是唯一的方法,那么Spring是否会公开一个递归扫描类层次结构以进行(元)注释的方法(因为大多数Spring注释可以用作元注释)?

java spring spring-ioc

3
推荐指数
1
解决办法
332
查看次数

Spring找不到Autowired接口实现

我这里有一个主要的 SpringBootApplication 类:

package com.example.springproj;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

@RestController 类在这里:

package com.example.springproj.controller;

@RestController
@Api("Sample")
public class RefDataController {

    @Autowired
    @Qualifier("RefDataServiceImpl")
    private RefDataService refDataService;

    @GetMapping(path = {"/refdata"}, produces = {"application/json"})
    public ResponseEntity<Configuration> getRefData() {
        // etc
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器自动连接此接口:

package com.example.springproj.service;

public interface RefDataService {

    Configuration getConfiguration(String param);
}
Run Code Online (Sandbox Code Playgroud)

这是由这个类实现的:

package com.example.springproj.services;
@Service
public class RefDataServiceImpl implements RefDataService {

    @Autowired
    private ConfigRepository config;

    @Value("${ENV}")
    private String environment;

    @Override
    public …
Run Code Online (Sandbox Code Playgroud)

spring dependency-injection spring-ioc spring-boot

3
推荐指数
1
解决办法
5621
查看次数

Autowire不适用于Spring Boot中的自定义UserDetailsS​​ervice

Spring启动应用程序启动,tomcat运行,然后在最终死亡之前抛出错误.

错误

运行我的应用程序给我这个Autowired错误:

2016-07-29 02:18:24.737 ERROR 44715 --- [  restartedMain] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private myapp.MyUserDetailsService myapp.WebSecurityConfig.userDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [myapp.MyUserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
Run Code Online (Sandbox Code Playgroud)

细节

我的安全配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends …
Run Code Online (Sandbox Code Playgroud)

java spring spring-ioc spring-boot

2
推荐指数
1
解决办法
7528
查看次数

Autowired ApplicationContext 没有方法 getBean

我在 RestController 类中自动装配了 ApplicationContext,因为我需要为收到的每个请求创建一个原型 bean。

为了创建 bean,我尝试了 context.getBean(xx) 但 context 没有列出 getBean() 方法。有没有办法可以在 RestController 类中获取原型类的 bean。我将此应用程序作为 Spring boot 运行。

示例代码在这里:

@RestController
@RequestMapping("/Restcompare")
public class CompareService {


    @Autowired
    private ApplicationContext context;

    private Comparator comparator;

    @RequestMapping("/compare")
    public String vcompare(@RequestParam(value="pre", defaultValue="") 
    String pre, @RequestParam(value="post", defaultValue="") String post){


        comparator = context.getBean(Comparator.class);  //Error here
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

解决方案: IDE 不知何故导入了 Spring 框架之外的不同 ApplicationContext。更正导入以org.springframework.context.ApplicationContext解决问题。

spring spring-ioc spring-boot spring-restcontroller spring-rest

2
推荐指数
1
解决办法
2876
查看次数

@ComponentScan和@Component背后的魔力

我仍在深入学习spring依赖注入。

我的第一个类是配置类,在这里我向容器声明以加载和管理在带注释的方法中声明的bean。

package ioc.question_004;

import ioc.commun.Person;
import ioc.commun.Profession;
import org.springframework.context.annotation.*;

@Configuration
public class MyConfiguration {

    @Bean
    public Profession profession(){
        return Profession.builder()
                     .name("professor")
                     .description("professor in the university")
                     .build();
    }

    @Bean
    public Person person(){
        return Person.builder()
                     .name("Bagna")
                     .age(52)
                     .profession(profession())
                     .build();
    }

}
Run Code Online (Sandbox Code Playgroud)

我的第二个类是daoRepository,它看起来像:

package ioc.question_008.dao;

import ioc.commun.Person;
import lombok.*;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
@Builder
@Setter
@Getter
@EqualsAndHashCode
@ToString
public class MyDaoRepository implements dao {

    List<Person> personList = new ArrayList<>();

    @Override
    public boolean save( Person person ){
        return this.personList.add(person);
    } …
Run Code Online (Sandbox Code Playgroud)

java spring autowired spring-ioc

2
推荐指数
1
解决办法
87
查看次数

Spring Controller 注入的属性变为 Null

我的情况非常类似于“将文件资源注入 Spring bean

我有一个使用一些 .jasper 编译文件的控制器,我正在声明它们

//...
@Controller
public class InvoicingController {

private Resource quoteTemplate;
...//
Run Code Online (Sandbox Code Playgroud)

在我的上下文配置文件中

<bean id="invoicingController" class="x.x.InvoicingController">
    <property name="quoteTemplate" value="/WEB-INF/jasper/Quote.jasper" />
...
Run Code Online (Sandbox Code Playgroud)

我在setQuoteTemplate()函数上设置了一个断点,它正在被调用,并且Resource在我初始化容器时正确设置了对象。但是,当我实际点击控制器时,控制器quoteTemplate为空。

我的理解是控制器是单例,除非我的理解存在差距,否则当我点击控制器处理的 url 时,我不确定为什么在容器初始化期间设置的值变为 null。

编辑:

谢谢@Sotirios Delimanolis

我最终将 bean 声明为:

    <bean id="quoteFile" class="java.io.File">
        <constructor-arg value="resources/jasper/Quote.jasper" />
    </bean>

    <bean id="quoteTemplate" class="org.springframework.core.io.FileSystemResource">
        <constructor-arg ref="quoteFile" />
    </bean>
Run Code Online (Sandbox Code Playgroud)

然后@Autowire像这样 ing 依赖项

@Autowired @Qualifier("quoteTemplate") private Resource quoteTemplate;
Run Code Online (Sandbox Code Playgroud)

@Qualifier使用是因为我有多个Resource实现类声明为 bean,这确保使用正确的一个。

java spring spring-mvc spring-ioc

1
推荐指数
1
解决办法
1305
查看次数