如何将JavaEE的@EJB、@Inject相关代码改写为Spring MVC适配版本
JavaEE代码转Spring MVC实现方案
核心注解对应关系
你最关注的JavaEE到Spring的注解替换规则如下:
@EJB替换为Spring的@Autowired注解,用于依赖注入@Inject可以直接保留(Spring原生支持JSR-330注解),也可以替换为@Autowired,Logger注入也可以用@Slf4j注解简化(需要引入lombok依赖)@Stateless无状态Bean替换为@Service注解,标注在业务层类上@Named+@ViewScoped如果你是用来做Web层页面交互的类,替换为@Controller+ 对应的作用域注解(单页交互常用@RequestScope/@SessionScope,默认是单例)@PersistenceContext注入EntityManager的写法,在Spring Data JPA下可以完全省略,直接继承JpaRepository调用封装好的CRUD方法即可
修正后的完整Spring代码
1. 实体类(注意拼写统一,避免字段名、类名拼写错误)
// AuthorEntity.java @Entity public class AuthorEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String authorName; // 注意原拼写是auther,建议修正为标准拼写author private String birthPlace; // 构造方法、getter、setter省略 }
2. Repository层(你写的代码基本正确,调整拼写即可)
@Repository public interface AuthorRepository extends JpaRepository<AuthorEntity, Long> { }
3. Service层(合并原Bookshelf的功能,替换@EJB注入)
@Service @Transactional public class BookService { @Autowired private AuthorRepository authorRepository; @Autowired private BookTitleRepository bookTitleRepository; // 注意注入要加@Autowired // 原Bookshelf的create方法直接调用JpaRepository的save方法即可 public void createAuthor(AuthorEntity author) { authorRepository.save(author); } }
4. Web层(替换原BookshelfService的@Named/@ViewScoped写法)
@Controller @RequestScope // 对应原@ViewScoped的请求级作用域,可根据业务调整 public class BookshelfController implements Serializable { private Long id; private String authorName; private String birthPlace; @Autowired private BookService bookService; // 注入Logger,也可以用@Slf4j简化 private transient Logger log = LoggerFactory.getLogger(this.getClass()); public String create() { AuthorEntity author = new AuthorEntity(id, authorName, birthPlace); bookService.createAuthor(author); // 这里返回视图名或者重定向地址,比如"redirect:/author/list" return null; } public String edit(AuthorEntity author) { id = author.getId(); authorName = author.getAuthorName(); birthPlace = author.getBirthPlace(); // 这里返回编辑页视图名,比如"author/edit" return null; } // getter setter省略 }
注意事项
- 你原代码里多处出现
auther的拼写错误,建议统一修正为author避免后续映射报错 - Spring MVC的Controller方法可以直接接收前端参数,不需要单独声明属性接收,也可以根据业务调整写法
- 如果没有引入lombok,Logger可以直接用LoggerFactory初始化即可,不需要额外注解
内容的提问来源于stack exchange,提问作者Aledun
相关产品推荐
相关产品推荐

