bean define java 赋值,Spring使用Java配置在会话范围内定义Bean

I would like to use a bean in session scope, but I receive an error:

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\testRestService\WEB-INF\classes\test\server\config\AppConfig.class];

nested exception is java.lang.annotation.AnnotationFormatError: Invalid default: public abstract org.springframework.beans.factory.annotation.Autowire org.springframework.config.java.annotation.Bean.autowire()

The Person Bean:

public class Person {

//This is a Pojo

//...

}

The AppConfig:

@Configuration

@EnableWebMvc

@ComponentScan("test.server")

public class AppConfig extends WebMvcConfigurerAdapter {

@Bean(scope = DefaultScopes.SESSION)

@ScopedProxy

public Person getPerson() {

return new Person();

}

}

The Person Sercive:

@Component

public class PersonService implements IPersonService {

@Autowired

protected Person person;

@Override

public void setPerson(Person person) {

this.person = person;

}

@Override

public Person getPerson() {

return this.person;

}

}

The PersonController:

@RestController()

@RequestMapping("/person")

public class PersonController {

@Autowired

private IPersonService personService;

@InitBinder

protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {

binder.registerCustomEditor(Person.class, new GenericEditor(Person.class));

}

@RequestMapping(value = "/setPerson", method = RequestMethod.GET)

public String setPerson(@RequestParam(value = "person") Person person) {

this.personService.setPerson(person);

return "Person: " + person + " saved.";

}

@RequestMapping(value = "/getPerson", method = RequestMethod.GET)

public Person getPerson() {

return this.personService.getPerson();

}

}

I tried to use @Scope("session") on the Person bean, in this case I did not use the @ScopedProxy annotation in appconfig and used the @org.springframework.context.annotation.Bean("person") instead of org.springframework.config.java.annotation.Bean(scope = DefaultScopes.SESSION). In this case I didn't receive an error, but the Person bean wasn't in the session scope when I tested it.

Thanks for the help.

解决方案

Session level beans are supported through JDK dynamic proxies. The following modifications are required in your code:

remove the getPerson() method from the AppConfig class

do not autowire your bean in PersonService, just instantiate it with it's default constructor

annotate the PersonService with the following:

@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值