5 | @for(entity <- entities){
6 | Email: @entity.getEmail
7 | }
8 | }
--------------------------------------------------------------------------------
/examples/spring-java/app/config/PlaySpringDIConfiguration.java:
--------------------------------------------------------------------------------
1 | package config;
2 |
3 | import org.springframework.context.annotation.ComponentScan;
4 | import org.springframework.context.annotation.Configuration;
5 |
6 | @Configuration
7 | @ComponentScan({"controllers"})
8 | public class PlaySpringDIConfiguration {
9 |
10 | }
--------------------------------------------------------------------------------
/examples/spring-java-jpa-spring-data/app/config/PlaySpringDIConfiguration.java:
--------------------------------------------------------------------------------
1 | package config;
2 |
3 | import org.springframework.context.annotation.ComponentScan;
4 | import org.springframework.context.annotation.Configuration;
5 |
6 | @Configuration
7 | @ComponentScan({"controllers"})
8 | public class PlaySpringDIConfiguration {
9 |
10 | }
--------------------------------------------------------------------------------
/examples/spring-java-jpa-spring-data/app/repositories/MyEntityRepository.java:
--------------------------------------------------------------------------------
1 | package repositories;
2 |
3 | import model.MyEntity;
4 | import org.springframework.data.jpa.repository.JpaRepository;
5 | import org.springframework.stereotype.Repository;
6 |
7 | @Repository
8 | public interface MyEntityRepository extends JpaRepository {
9 |
10 | }
--------------------------------------------------------------------------------
/project/plugins.sbt:
--------------------------------------------------------------------------------
1 | logLevel := Level.Warn
2 |
3 | val InterplayVersion = sys.props.get("interplay.version").getOrElse("1.3.12")
4 |
5 | addSbtPlugin("com.typesafe.play" % "interplay" % InterplayVersion)
6 | addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.6")
7 | addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.8.1")
8 | addSbtPlugin("de.heikoseeberger" % "sbt-header" % "3.0.2")
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: scala
2 | scala:
3 | - 2.12.4
4 | - 2.11.11
5 | jdk:
6 | - openjdk8
7 | script:
8 | - sbt ++$TRAVIS_SCALA_VERSION validateCode test
9 | cache:
10 | directories:
11 | - "$HOME/.ivy2/cache"
12 | before_cache:
13 | - rm -rf $HOME/.ivy2/cache/com.lightbend.play/*
14 | - rm -rf $HOME/.ivy2/cache/scala_*/sbt_*/com.lightbend.play/*
15 | - find $HOME/.ivy2/cache -name "ivydata-*.properties" -print0 | xargs -n10 -0 rm
16 |
--------------------------------------------------------------------------------
/examples/spring-java/conf/routes:
--------------------------------------------------------------------------------
1 | # Routes
2 | # This file defines all application routes (Higher priority routes first)
3 | # ~~~~
4 |
5 | # An example controller showing a sample home page
6 | GET / controllers.HomeController.index
7 |
8 | # Map static resources from the /public folder to the /assets URL path
9 | GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
10 |
--------------------------------------------------------------------------------
/examples/spring-java-jpa-spring-data/conf/routes:
--------------------------------------------------------------------------------
1 | # Routes
2 | # This file defines all application routes (Higher priority routes first)
3 | # ~~~~
4 |
5 | # An example controller showing a sample home page
6 | GET / controllers.HomeController.index
7 |
8 | # Map static resources from the /public folder to the /assets URL path
9 | GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
10 |
--------------------------------------------------------------------------------
/examples/spring-java/build.sbt:
--------------------------------------------------------------------------------
1 | name := """spring-java"""
2 | organization := "com.example"
3 |
4 | version := "1.0-SNAPSHOT"
5 |
6 | lazy val root = (project in file(".")).enablePlugins(PlayJava)
7 |
8 | scalaVersion := "2.12.3"
9 |
10 | val SpringVersion = "4.3.11.RELEASE"
11 |
12 | libraryDependencies ++= Seq(
13 | "com.lightbend.play" %% "play-spring-loader" % "0.0.2",
14 | "org.springframework" % "spring-core" % SpringVersion,
15 | "org.springframework" % "spring-expression" % SpringVersion,
16 | "org.springframework" % "spring-aop" % SpringVersion
17 | )
18 |
--------------------------------------------------------------------------------
/examples/spring-java-jpa-spring-data/build.sbt:
--------------------------------------------------------------------------------
1 | name := """spring-java-jpa-spring-data"""
2 | organization := "com.example"
3 |
4 | version := "1.0-SNAPSHOT"
5 |
6 | lazy val root = (project in file(".")).enablePlugins(PlayJava)
7 |
8 | scalaVersion := "2.12.3"
9 |
10 | val SpringVersion = "4.3.11.RELEASE"
11 |
12 | libraryDependencies ++= Seq(
13 | javaJdbc,
14 | "com.lightbend.play" %% "play-spring-loader" % "0.0.2",
15 | "org.springframework.data" % "spring-data-jpa" % "1.11.8.RELEASE",
16 | "org.hibernate" % "hibernate-entitymanager" % "5.2.12.Final",
17 | "com.h2database" % "h2" % "1.4.196"
18 | )
19 |
--------------------------------------------------------------------------------
/examples/spring-java-jpa-spring-data/app/model/AbstractEntity.java:
--------------------------------------------------------------------------------
1 | package model;
2 |
3 | import java.io.Serializable;
4 |
5 | import javax.persistence.GeneratedValue;
6 | import javax.persistence.GenerationType;
7 | import javax.persistence.Id;
8 | import javax.persistence.MappedSuperclass;
9 |
10 | @MappedSuperclass
11 | public abstract class AbstractEntity implements Serializable {
12 |
13 | @Id
14 | @GeneratedValue(strategy = GenerationType.SEQUENCE)
15 | private Long id;
16 |
17 | public Long getId() {
18 | return id;
19 | }
20 |
21 | public void setId(Long id) {
22 | this.id = id;
23 | }
24 | }
--------------------------------------------------------------------------------
/examples/spring-java-jpa-spring-data/conf/application.conf:
--------------------------------------------------------------------------------
1 |
2 | play.application.loader = "com.lightbend.play.spring.SpringApplicationLoader"
3 |
4 | play.spring.configs = ["config.PlaySpringDIConfiguration", "config.PersistenceContext"]
5 |
6 | db {
7 | default {
8 | driver="org.h2.Driver"
9 | url="jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;"
10 | username="sa"
11 | password=""
12 | hibernate.dialect="org.hibernate.dialect.H2Dialect"
13 | hibernate.hbm2ddl.auto="create"
14 | hibernate.show_sql=false
15 | hibernate.format_sql=true
16 | hibernate.connection.autocommit=false
17 | }
18 | }
19 |
20 | # Which persistent unit should be used by JPA provider
21 | jpa.default=defaultPersistenceUnit
--------------------------------------------------------------------------------
/examples/spring-java/app/controllers/HomeController.java:
--------------------------------------------------------------------------------
1 | package controllers;
2 |
3 | import play.mvc.*;
4 |
5 | import org.springframework.stereotype.Component;
6 |
7 | /**
8 | * This controller contains an action to handle HTTP requests
9 | * to the application's home page.
10 | */
11 | @Component
12 | public class HomeController extends Controller {
13 |
14 | /**
15 | * An action that renders an HTML page with a welcome message.
16 | * The configuration in the routes file means that
17 | * this method will be called when the application receives a
18 | * GET request with a path of /.
19 | */
20 | public Result index() {
21 | return ok(views.html.index.render());
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/examples/spring-java-jpa-spring-data/app/model/MyEntity.java:
--------------------------------------------------------------------------------
1 | package model;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.Index;
6 | import javax.persistence.Table;
7 | import javax.validation.constraints.NotNull;
8 | import javax.validation.constraints.Size;
9 |
10 | import org.hibernate.validator.constraints.Email;
11 | import org.hibernate.validator.constraints.NotBlank;
12 |
13 | @Entity
14 | @Table
15 | public class MyEntity extends AbstractEntity {
16 | @Email
17 | @NotBlank
18 | @Size(max = 254)
19 | @Column(name = "email", length = 254, nullable = false, unique = true)
20 | private String email;
21 |
22 | public String getEmail() {
23 | return email;
24 | }
25 |
26 | public void setEmail(String email) {
27 | this.email = email;
28 | }
29 | }
--------------------------------------------------------------------------------
/examples/spring-java/test/controllers/HomeControllerTest.java:
--------------------------------------------------------------------------------
1 | package controllers;
2 |
3 | import com.lightbend.play.spring.SpringApplicationBuilder;
4 | import org.junit.Test;
5 | import play.Application;
6 | import play.mvc.Http;
7 | import play.mvc.Result;
8 | import play.test.WithApplication;
9 |
10 | import static org.junit.Assert.assertEquals;
11 | import static play.mvc.Http.Status.OK;
12 | import static play.test.Helpers.GET;
13 | import static play.test.Helpers.route;
14 |
15 | public class HomeControllerTest extends WithApplication {
16 |
17 | @Override
18 | protected Application provideApplication() {
19 | return new SpringApplicationBuilder().build().asJava();
20 | }
21 |
22 | @Test
23 | public void testIndex() {
24 | Http.RequestBuilder request = new Http.RequestBuilder()
25 | .method(GET)
26 | .uri("/");
27 |
28 | Result result = route(app, request);
29 | assertEquals(OK, result.status());
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/examples/spring-java-jpa-spring-data/test/controllers/HomeControllerTest.java:
--------------------------------------------------------------------------------
1 | package controllers;
2 |
3 | import com.lightbend.play.spring.SpringApplicationBuilder;
4 | import org.junit.Test;
5 | import play.Application;
6 | import play.mvc.Http;
7 | import play.mvc.Result;
8 | import play.test.WithApplication;
9 |
10 | import static org.junit.Assert.assertEquals;
11 | import static play.mvc.Http.Status.OK;
12 | import static play.test.Helpers.GET;
13 | import static play.test.Helpers.route;
14 |
15 | public class HomeControllerTest extends WithApplication {
16 |
17 | @Override
18 | protected Application provideApplication() {
19 | return new SpringApplicationBuilder().build().asJava();
20 | }
21 |
22 | @Test
23 | public void testIndex() {
24 | Http.RequestBuilder request = new Http.RequestBuilder()
25 | .method(GET)
26 | .uri("/");
27 |
28 | Result result = route(app, request);
29 | assertEquals(OK, result.status());
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/scala/com/lightbend/play/spring/PlayModuleBeanDefinitionReader.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Lightbend
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.lightbend.play.spring
18 |
19 | import org.springframework.beans.factory.support.DefaultListableBeanFactory
20 | import play.api.inject.Binding
21 |
22 | trait PlayModuleBeanDefinitionReader {
23 |
24 | def bind(beanFactory: DefaultListableBeanFactory, binding: Binding[_])
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/examples/spring-java/app/views/main.scala.html:
--------------------------------------------------------------------------------
1 | @*
2 | * This template is called from the `index` template. This template
3 | * handles the rendering of the page header and body tags. It takes
4 | * two arguments, a `String` for the title of the page and an `Html`
5 | * object to insert into the body of the page.
6 | *@
7 | @(title: String)(content: Html)
8 |
9 |
10 |
11 |
12 | @* Here's where we render the page title `String`. *@
13 | @title
14 |
15 |
16 |
17 |
18 | @* And here's where we render the `Html` object containing
19 | * the page content. *@
20 | @content
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/examples/spring-java-jpa-spring-data/app/views/main.scala.html:
--------------------------------------------------------------------------------
1 | @*
2 | * This template is called from the `index` template. This template
3 | * handles the rendering of the page header and body tags. It takes
4 | * two arguments, a `String` for the title of the page and an `Html`
5 | * object to insert into the body of the page.
6 | *@
7 | @(title: String)(content: Html)
8 |
9 |
10 |
11 |
12 | @* Here's where we render the page title `String`. *@
13 | @title
14 |
15 |
16 |
17 |
18 | @* And here's where we render the `Html` object containing
19 | * the page content. *@
20 | @content
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/examples/spring-java-jpa-spring-data/app/controllers/HomeController.java:
--------------------------------------------------------------------------------
1 | package controllers;
2 |
3 | import play.mvc.*;
4 | import java.util.Random;
5 | import javax.inject.Inject;
6 | import model.MyEntity;
7 | import repositories.MyEntityRepository;
8 | import org.springframework.stereotype.Component;
9 |
10 | /**
11 | * This controller contains an action to handle HTTP requests
12 | * to the application's home page.
13 | */
14 | @Component
15 | public class HomeController extends Controller {
16 |
17 | @Inject
18 | private MyEntityRepository repository;
19 |
20 | /**
21 | * An action that renders an HTML page with a welcome message.
22 | * The configuration in the routes file means that
23 | * this method will be called when the application receives a
24 | * GET request with a path of /.
25 | */
26 | public Result index() {
27 | MyEntity entity = new MyEntity();
28 | entity.setEmail("test"+new Random().nextInt()+"@test.com");
29 | repository.save(entity);
30 | return ok(views.html.index.render(repository.findAll()));
31 | }
32 | }
--------------------------------------------------------------------------------
/examples/spring-java/conf/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | ${application.home:-.}/logs/application.log
8 |
9 | %date [%level] from %logger in %thread - %message%n%xException
10 |
11 |
12 |
13 |
14 |
15 | %coloredLevel %logger{15} - %message%n%xException{10}
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/examples/spring-java-jpa-spring-data/conf/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | ${application.home:-.}/logs/application.log
8 |
9 | %date [%level] from %logger in %thread - %message%n%xException
10 |
11 |
12 |
13 |
14 |
15 | %coloredLevel %logger{15} - %message%n%xException{10}
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/src/test/java/com/lightbend/play/spring/SpringApplicationBuilderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Lightbend
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.lightbend.play.spring;
18 |
19 | import javax.inject.Provider;
20 | import javax.inject.Singleton;
21 |
22 | import org.junit.Test;
23 | import play.api.Application;
24 | import play.api.Configuration;
25 | import play.api.Environment;
26 | import play.api.inject.Binding;
27 | import play.api.inject.Module;
28 | import scala.collection.Seq;
29 |
30 | import static org.junit.Assert.assertEquals;
31 | import static org.junit.Assert.assertTrue;
32 |
33 | public class SpringApplicationBuilderTest {
34 |
35 | static class Foo {
36 | static boolean created = false;
37 | Foo() { created = true; }
38 | }
39 |
40 | static class FooProvider implements Provider {
41 | public Foo get() {
42 | return new Foo();
43 | }
44 | }
45 |
46 | @Test
47 | public void testSingletonProvider() {
48 | Foo.created = false;
49 |
50 | SpringApplicationBuilder builder = new SpringApplicationBuilder()
51 | .bindings(new Module() {
52 | public Seq> bindings(Environment environment, Configuration configuration) {
53 | return seq(
54 | bind(Foo.class).toProvider(FooProvider.class).in(Singleton.class)
55 | );
56 | }
57 | });
58 | Application app = builder.build();
59 |
60 | // check eagerness
61 | assertTrue(Foo.created);
62 |
63 | // check singleton property
64 | assertEquals(app.injector().instanceOf(Foo.class), app.injector().instanceOf(Foo.class));
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/examples/spring-java-jpa-spring-data/app/config/PersistenceContext.java:
--------------------------------------------------------------------------------
1 | package config;
2 |
3 | import java.util.Properties;
4 |
5 | import javax.persistence.EntityManagerFactory;
6 | import javax.sql.DataSource;
7 |
8 | import org.apache.commons.lang3.ClassUtils;
9 | import org.springframework.context.annotation.Bean;
10 | import org.springframework.context.annotation.Configuration;
11 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
12 | import org.springframework.orm.jpa.JpaTransactionManager;
13 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
14 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
15 | import org.springframework.transaction.annotation.EnableTransactionManagement;
16 |
17 | import com.typesafe.config.Config;
18 |
19 | import model.AbstractEntity;
20 | import play.db.DBApi;
21 |
22 | @Configuration
23 | @EnableTransactionManagement
24 | @EnableJpaRepositories("repositories")
25 | public class PersistenceContext {
26 |
27 | @Bean
28 | DataSource dataSource(DBApi dbapi) {
29 | return dbapi.getDatabase("default").getDataSource();
30 | }
31 |
32 | @Bean
33 | LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, Config config) {
34 | Config hibernateConfig = config.getConfig("db.default.hibernate");
35 |
36 | LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
37 | entityManagerFactoryBean.setDataSource(dataSource);
38 | entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
39 | entityManagerFactoryBean.setPackagesToScan(ClassUtils.getPackageName(AbstractEntity.class));
40 |
41 | Properties jpaProperties = new Properties();
42 | hibernateConfig.entrySet().forEach(entry -> {
43 | jpaProperties.put("hibernate."+entry.getKey(), entry.getValue().unwrapped());
44 | });
45 | entityManagerFactoryBean.setJpaProperties(jpaProperties);
46 | entityManagerFactoryBean.setPersistenceUnitName(config.getString("jpa.default"));
47 |
48 | return entityManagerFactoryBean;
49 | }
50 |
51 | @Bean
52 | JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
53 | JpaTransactionManager transactionManager = new JpaTransactionManager();
54 | transactionManager.setEntityManagerFactory(entityManagerFactory);
55 | return transactionManager;
56 | }
57 | }
--------------------------------------------------------------------------------
/src/main/scala/com/lightbend/play/spring/SpringApplicationLoader.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Lightbend
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.lightbend.play.spring
18 |
19 | import controllers.Assets
20 | import play.api.ApplicationLoader.Context
21 | import play.api._
22 | import play.api.inject._
23 | import play.core.WebCommands
24 |
25 | /**
26 | * based on the awesome work of jroper:
27 | * https://github.com/jroper/play-spring
28 | */
29 | class SpringApplicationLoader(protected val initialBuilder: SpringApplicationBuilder) extends ApplicationLoader {
30 |
31 | // empty constructor needed for instantiating via reflection
32 | def this() = this(new SpringApplicationBuilder)
33 |
34 | def load(context: Context) = {
35 |
36 | builder(context).build()
37 | }
38 |
39 | /**
40 | * Construct a builder to use for loading the given context.
41 | */
42 | protected def builder(context: ApplicationLoader.Context): SpringApplicationBuilder = {
43 | initialBuilder
44 | .in(context.environment)
45 | .loadConfig(context.initialConfiguration)
46 | .overrides(overrides(context): _*)
47 | }
48 |
49 | /**
50 | * Override some bindings using information from the context. The default
51 | * implementation of this method provides bindings that most applications
52 | * should include.
53 | */
54 | protected def overrides(context: ApplicationLoader.Context): Seq[Module] = {
55 | SpringApplicationLoader.defaultOverrides(context)
56 | }
57 | }
58 |
59 | private object SpringApplicationLoader {
60 |
61 | /**
62 | * The default overrides provided by the Scala and Java SpringApplicationLoaders.
63 | */
64 | def defaultOverrides(context: ApplicationLoader.Context) = {
65 | Seq(
66 | new Module {
67 | def bindings(environment: Environment, configuration: Configuration) = Seq(
68 | bind[OptionalSourceMapper] to new OptionalSourceMapper(context.sourceMapper),
69 | bind[WebCommands] to context.webCommands,
70 | bind[Assets].to[Assets],
71 | bind[play.Configuration].to[play.Configuration])
72 | })
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/scala/com/lightbend/play/spring/RootBeanDefinitionCreator.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Lightbend
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.lightbend.play.spring
18 |
19 | import org.springframework.beans.MutablePropertyValues
20 | import org.springframework.beans.factory.config.{ ConstructorArgumentValues, BeanDefinition }
21 | import org.springframework.beans.factory.support.{ MethodOverrides, AbstractBeanDefinition, RootBeanDefinition }
22 |
23 | object RootBeanDefinitionCreator {
24 |
25 | def create(bd: BeanDefinition): RootBeanDefinition = {
26 | val rbd = new RootBeanDefinition()
27 | rbd.setParentName(bd.getParentName)
28 | rbd.setBeanClassName(bd.getBeanClassName)
29 | rbd.setFactoryBeanName(bd.getFactoryBeanName)
30 | rbd.setFactoryMethodName(bd.getFactoryMethodName)
31 | rbd.setScope(bd.getScope)
32 | rbd.setAbstract(bd.isAbstract)
33 | rbd.setLazyInit(bd.isLazyInit)
34 | rbd.setRole(bd.getRole)
35 | rbd.setConstructorArgumentValues(new ConstructorArgumentValues(bd.getConstructorArgumentValues))
36 | rbd.setPropertyValues(new MutablePropertyValues(bd.getPropertyValues))
37 | rbd.setSource(bd.getSource)
38 |
39 | val attributeNames = bd.attributeNames
40 | for (attributeName <- attributeNames) {
41 | rbd.setAttribute(attributeName, bd.getAttribute(attributeName))
42 | }
43 |
44 | bd match {
45 | case originalAbd: AbstractBeanDefinition =>
46 | if (originalAbd.hasBeanClass) {
47 | rbd.setBeanClass(originalAbd.getBeanClass)
48 | }
49 | rbd.setAutowireMode(originalAbd.getAutowireMode)
50 | rbd.setDependencyCheck(originalAbd.getDependencyCheck)
51 | rbd.setDependsOn(originalAbd.getDependsOn: _*)
52 | rbd.setAutowireCandidate(originalAbd.isAutowireCandidate)
53 | rbd.copyQualifiersFrom(originalAbd)
54 | rbd.setPrimary(originalAbd.isPrimary)
55 | rbd.setNonPublicAccessAllowed(originalAbd.isNonPublicAccessAllowed)
56 | rbd.setLenientConstructorResolution(originalAbd.isLenientConstructorResolution)
57 | rbd.setInitMethodName(originalAbd.getInitMethodName)
58 | rbd.setEnforceInitMethod(originalAbd.isEnforceInitMethod)
59 | rbd.setDestroyMethodName(originalAbd.getDestroyMethodName)
60 | rbd.setEnforceDestroyMethod(originalAbd.isEnforceDestroyMethod)
61 | rbd.setMethodOverrides(new MethodOverrides(originalAbd.getMethodOverrides))
62 | rbd.setSynthetic(originalAbd.isSynthetic)
63 | rbd.setResource(originalAbd.getResource)
64 |
65 | case _ => rbd.setResourceDescription(bd.getResourceDescription)
66 | }
67 |
68 | rbd
69 | }
70 | }
--------------------------------------------------------------------------------
/src/main/scala/com/lightbend/play/spring/SpringInjector.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Lightbend
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.lightbend.play.spring
18 |
19 | import org.springframework.beans.BeanInstantiationException
20 | import org.springframework.beans.factory.config.{ AutowireCapableBeanFactory, BeanDefinition }
21 | import org.springframework.beans.factory.{ BeanCreationException, NoSuchBeanDefinitionException }
22 | import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
23 | import org.springframework.beans.factory.support.{ GenericBeanDefinition, DefaultListableBeanFactory }
24 | import play.api.inject.{ BindingKey, Injector, Modules, Module }
25 | import play.api.{ PlayException, Configuration, Environment }
26 |
27 | import scala.reflect.ClassTag
28 |
29 | class SpringInjector(factory: DefaultListableBeanFactory) extends Injector {
30 |
31 | private val bpp = new AutowiredAnnotationBeanPostProcessor()
32 | bpp.setBeanFactory(factory)
33 |
34 | def instanceOf[T](implicit ct: ClassTag[T]) = instanceOf(ct.runtimeClass).asInstanceOf[T]
35 |
36 | def instanceOf[T](clazz: Class[T]) = {
37 | getBean(clazz)
38 | }
39 |
40 | def getBean[T](clazz: Class[T]): T = {
41 | try {
42 | factory.getBean(clazz)
43 | } catch {
44 |
45 | case e: NoSuchBeanDefinitionException =>
46 | // if the class is a concrete type, attempt to create a just in time binding
47 | if (!clazz.isInterface /* todo check if abstract, how? */ ) {
48 | tryCreate(clazz)
49 | } else {
50 | throw e
51 | }
52 |
53 | case e: BeanInstantiationException =>
54 | throw e
55 |
56 | case e: BeanCreationException =>
57 | throw e
58 |
59 | case e: Exception => throw e
60 | }
61 | }
62 |
63 | override def instanceOf[T](key: BindingKey[T]): T = {
64 | getBean(key.clazz)
65 | }
66 |
67 | def tryCreate[T](clazz: Class[T]) = {
68 | val beanDef = new GenericBeanDefinition()
69 | beanDef.setScope(BeanDefinition.SCOPE_PROTOTYPE)
70 | SpringBuilder.maybeSetScope(beanDef, clazz)
71 | beanDef.setBeanClass(clazz)
72 |
73 | /**
74 | * Set primary to make sure this class is selected over the "parent" one declared in the bindings which is likely
75 | * to be an interface or provider.
76 | * See interface play.api.routing.Router and actual class router.Routes
77 | */
78 | beanDef.setPrimary(true)
79 |
80 | beanDef.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT)
81 | factory.registerBeanDefinition(clazz.toString, beanDef)
82 | factory.clearMetadataCache()
83 |
84 | val bean = instanceOf(clazz)
85 |
86 | // todo - this ensures fields get injected, see if there's a way that this can be done automatically
87 | bpp.processInjection(bean)
88 | bean
89 | }
90 | }
91 |
92 | object SpringableModule {
93 |
94 | def loadModules(environment: Environment, configuration: Configuration): Seq[Module] = {
95 | Modules.locate(environment, configuration) map springable
96 | }
97 |
98 | /**
99 | * Attempt to convert a module of unknown type to a GuiceableModule.
100 | */
101 | def springable(module: Any): Module = module match {
102 | case playModule: Module => playModule
103 | // case bin
104 | case unknown => throw new PlayException(
105 | "Unknown module type",
106 | s"Module [$unknown] is not a Play module")
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/main/scala/com/lightbend/play/spring/SpringApplicationBuilder.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Lightbend
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.lightbend.play.spring
18 |
19 | import play.api.inject.{ bind, _ }
20 | import play.api._
21 | import play.core.{ DefaultWebCommands, WebCommands }
22 |
23 | /**
24 | * A builder for creating Applications using Spring.
25 | */
26 | class SpringApplicationBuilder(
27 | environment: Environment = Environment.simple(),
28 | configuration: Configuration = Configuration.empty,
29 | modules: Seq[Module] = Seq.empty,
30 | overrides: Seq[Module] = Seq.empty,
31 | disabled: Seq[Class[_]] = Seq.empty,
32 | loadConfiguration: Environment => Configuration = Configuration.load,
33 | loadModules: (Environment, Configuration) => Seq[Module] = SpringableModule.loadModules,
34 | beanReader: PlayModuleBeanDefinitionReader = DefaultPlayModuleBeanDefinitionReader()) extends SpringBuilder[SpringApplicationBuilder](
35 | environment, configuration, modules, overrides, disabled, beanReader) {
36 |
37 | // extra constructor for creating from Java
38 | def this() = this(environment = Environment.simple())
39 |
40 | /**
41 | * Create a new Self for this immutable builder.
42 | * Provided by builder implementations.
43 | */
44 | override protected def newBuilder(
45 | environment: Environment,
46 | configuration: Configuration,
47 | modules: Seq[Module], overrides: Seq[Module],
48 | disabled: Seq[Class[_]],
49 | beanReader: PlayModuleBeanDefinitionReader): SpringApplicationBuilder = {
50 | copy(environment, configuration, modules, overrides, disabled, beanReader)
51 | }
52 |
53 | override def prepareConfig(): SpringApplicationBuilder = {
54 | val initialConfiguration = loadConfiguration(environment)
55 | val appConfiguration = initialConfiguration ++ configuration
56 |
57 | LoggerConfigurator(environment.classLoader).foreach {
58 | _.configure(environment)
59 | }
60 |
61 | if (shouldDisplayLoggerDeprecationMessage(appConfiguration)) {
62 | Logger.warn("Logger configuration in conf files is deprecated and has no effect. Use a logback configuration file instead.")
63 | }
64 |
65 | val loadedModules = loadModules(environment, appConfiguration)
66 |
67 | copy(configuration = appConfiguration)
68 | .bindings(loadedModules: _*)
69 | .bindings(new Module {
70 | override def bindings(env: Environment, conf: Configuration): Seq[Binding[_]] = Seq(
71 | bind[OptionalSourceMapper] to new OptionalSourceMapper(None),
72 | bind[WebCommands] to new DefaultWebCommands)
73 | })
74 | }
75 |
76 | /**
77 | * Checks if the path contains the logger path
78 | * and whether or not one of the keys contains a deprecated value
79 | * TODO: extract to class to be reused across Guice and Spring
80 | *
81 | * @param appConfiguration The app configuration
82 | * @return Returns true if one of the keys contains a deprecated value, otherwise false
83 | */
84 | def shouldDisplayLoggerDeprecationMessage(appConfiguration: Configuration): Boolean = {
85 | import scala.collection.JavaConverters._
86 | import scala.collection.mutable
87 |
88 | val deprecatedValues = List("DEBUG", "WARN", "ERROR", "INFO", "TRACE", "OFF")
89 |
90 | // Recursively checks each key to see if it contains a deprecated value
91 | def hasDeprecatedValue(values: mutable.Map[String, AnyRef]): Boolean = {
92 | values.exists {
93 | case (_, value: String) if deprecatedValues.contains(value) =>
94 | true
95 | case (_, value: java.util.Map[String, AnyRef]) =>
96 | hasDeprecatedValue(value.asScala)
97 | case _ =>
98 | false
99 | }
100 | }
101 |
102 | if (appConfiguration.underlying.hasPath("logger")) {
103 | appConfiguration.underlying.getAnyRef("logger") match {
104 | case value: String =>
105 | hasDeprecatedValue(mutable.Map("logger" -> value))
106 | case value: java.util.Map[String, AnyRef] =>
107 | hasDeprecatedValue(value.asScala)
108 | case _ =>
109 | false
110 | }
111 | } else {
112 | false
113 | }
114 | }
115 |
116 | /**
117 | * Set the initial configuration loader.
118 | * Overrides the default or any previously configured values.
119 | */
120 | def loadConfig(loader: Environment => Configuration): SpringApplicationBuilder =
121 | copy(loadConfiguration = loader)
122 |
123 | /**
124 | * Set the initial configuration.
125 | * Overrides the default or any previously configured values.
126 | */
127 | def loadConfig(conf: Configuration): SpringApplicationBuilder =
128 | loadConfig(env => conf)
129 |
130 | /**
131 | * Set the module loader.
132 | * Overrides the default or any previously configured values.
133 | */
134 | def load(loader: (Environment, Configuration) => Seq[Module]): SpringApplicationBuilder =
135 | copy(loadModules = loader)
136 |
137 | /**
138 | * Create a new Play Application using this configured builder.
139 | */
140 | def build(): Application = {
141 | injector().instanceOf[Application]
142 | }
143 |
144 | override def injector(): Injector = {
145 | prepareConfig().bindings(createModules(): _*).springInjector()
146 | }
147 |
148 | /**
149 | * Internal copy method with defaults.
150 | */
151 | private def copy(
152 | environment: Environment = environment,
153 | configuration: Configuration = configuration,
154 | modules: Seq[Module] = modules,
155 | overrides: Seq[Module] = overrides,
156 | disabled: Seq[Class[_]] = disabled,
157 | beanReader: PlayModuleBeanDefinitionReader = beanReader,
158 | loadConfiguration: Environment => Configuration = loadConfiguration,
159 | loadModules: (Environment, Configuration) => Seq[Module] = loadModules): SpringApplicationBuilder =
160 | new SpringApplicationBuilder(environment, configuration, modules, overrides, disabled, loadConfiguration, loadModules, beanReader)
161 | }
162 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # End of Life
2 |
3 | The active Playframework contributors consider this repository has reached End of Life and archived it.
4 |
5 | This repository is not being used anymore and won't get any further updates.
6 |
7 | Thank you to all contributors that worked on this repository!
8 |
9 |
10 | # Play Spring Loader
11 |
12 | This is an application loader for Play applications that runs with Spring as the DI. It binds and allows injecting all Play-provided components in addition to any components provided by third-party Play modules (defined as a `play.api.inject.Module`)
13 |
14 | The current version targets Play 2.6.x and Spring 4.3.x. It may work but has not been tested on other versions.
15 |
16 | The application loader was originally authored by Remi Thieblin based on the original proof of concept by James Roper. It is now being maintained by the Play team. There are currently no plans to add new features, but we're happy to accept contributions from the community. This project still needs tests and also a Java API for the SpringApplicationBuilder (though the Scala API can be used from Java).
17 |
18 | ## Setup Instructions
19 |
20 | To use in your Play SBT project, add the dependency to your `build.sbt`:
21 |
22 | ```scala
23 | libraryDependencies += "com.lightbend.play" %% "play-spring-loader" % "0.0.2"
24 | ```
25 |
26 | Then configure the loader in your `application.conf`:
27 |
28 | ```
29 | play.application.loader = "com.lightbend.play.spring.SpringApplicationLoader"
30 | ````
31 |
32 | ### For a Scala-based app
33 |
34 | ```sh
35 | play.application.loader = "com.lightbend.play.spring.SpringApplicationLoader"
36 |
37 | # This works assuming the class is a play.api.inject.Module
38 | #play.modules.enabled += "com.demo.spring.MyModule"
39 |
40 | play.spring.configs += "config.AppConfig"
41 | ```
42 |
43 | with the following configuration class:
44 |
45 | ```scala
46 | package config
47 |
48 | import org.springframework.context.annotation.{ComponentScan, Configuration}
49 |
50 | @Configuration
51 | @ComponentScan(Array("com.demo.spring", "controllers"))
52 | class AppConfig {
53 |
54 | }
55 | ```
56 |
57 | ### For a Java-based app
58 |
59 | ```sh
60 | play.application.loader = "com.lightbend.play.spring.SpringApplicationLoader"
61 |
62 | # This works assuming the class is a play.api.inject.Module
63 | #play.modules.enabled += "com.demo.spring.MyModule"
64 |
65 | play.spring.configs = ["com.example.PlaySpringDIConfiguration"]
66 | ```
67 |
68 | with the following configuration class:
69 |
70 | ```java
71 | package com.example;
72 |
73 | import org.springframework.context.annotation.ComponentScan;
74 | import org.springframework.context.annotation.Configuration;
75 |
76 | @Configuration
77 | @ComponentScan
78 | public class PlaySpringDIConfiguration {
79 |
80 | }
81 | ```
82 |
83 | ## Migrating from Guice
84 |
85 | If you want to migrate your existing project from `guice` you should follow these steps
86 |
87 | ### For app without JPA
88 |
89 | 1. Remove `guice` from your `libraryDependencies` in `build.sbt` file
90 | 2. Make sure `PlaySpringDIConfiguration` is placed in your root package or you have to name specific packages in `@ComponentScan` annotation
91 | 3. Annotate all of your controllers as `@Component` and services as `@Service`
92 | 4. Replace all `com.google.inject.Injector` with `org.springframework.context.ApplicationContext` and `injector.getInstance(MyClass.class)` with `context.getBean(MyClass.class)`
93 |
94 | ### For app with JPA
95 |
96 | Besides all of the above steps you must:
97 |
98 | 1. Remove `javaJpa` (`jpa`) from your `libraryDependencies` in `build.sbt` file
99 | 2. Add `"org.springframework" % "spring-orm" % "4.3.12.RELEASE"`, `"org.springframework" % "spring-aop" % "4.3.12.RELEASE"` and
100 | `"org.springframework" % "spring-expression" % "4.3.12.RELEASE"` to your `libraryDependencies` in `build.sbt` file
101 | 3. Place this class next to the `PlaySpringDIConfiguration` (or inside it):
102 | ```
103 | @Configuration
104 | @EnableTransactionManagement
105 | // @EnableJpaRepositories //For SpringData
106 | public class PersistenceContext {
107 |
108 | @Bean
109 | DataSource dataSource(play.db.DBApi dbapi) {
110 | return dbapi.getDatabase("default").getDataSource();
111 | }
112 |
113 | @Bean
114 | LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, Config config) {
115 | Config hibernateConfig = config.getConfig("db.default.hibernate");
116 |
117 | LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
118 | entityManagerFactoryBean.setDataSource(dataSource);
119 | entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
120 | entityManagerFactoryBean.setPackagesToScan("com.example.domain.model");
121 |
122 | Properties jpaProperties = new Properties();
123 | hibernateConfig.entrySet().forEach(entry -> {
124 | jpaProperties.put("hibernate."+entry.getKey(), entry.getValue().unwrapped());
125 | });
126 | entityManagerFactoryBean.setJpaProperties(jpaProperties);
127 | entityManagerFactoryBean.setPersistenceUnitName(config.getString("jpa.default"));
128 |
129 | return entityManagerFactoryBean;
130 | }
131 |
132 | @Bean
133 | JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
134 | JpaTransactionManager transactionManager = new JpaTransactionManager();
135 | transactionManager.setEntityManagerFactory(entityManagerFactory);
136 | return transactionManager;
137 | }
138 | }
139 | ```
140 | 4. Add these properties from your `persisttence.xml` in `db.default` section of your `application.conf`:
141 | ```
142 | db {
143 | default {
144 | [... your current db config ...]
145 | hibernate.dialect="org.hibernate.dialect.X"
146 | hibernate.hbm2ddl.auto="validate"
147 | hibernate.show_sql=false
148 | hibernate.format_sql=true
149 | hibernate.connection.autocommit=false
150 | }
151 | ```
152 | 5. Delete `persisttence.xml` file
153 | 6. Annotate all of your repositories as `@Repository`
154 | 7. Replace all `@Inject JPAApi jpaApi` with `@PersistenceContext EntityManager entityManager` and `jpaApi.em()` with `entityManager`
155 | 8. Replace all `play.db.jpa.Transactional` with `javax.transaction.Transactional`
156 |
157 | If you want to use SpringData, replace `"org.springframework" % "spring-orm" % "4.3.12.RELEASE"`, `"org.springframework" % "spring-aop" % "4.3.12.RELEASE"` and `"org.springframework" % "spring-expression" % "4.3.12.RELEASE"` with `"org.springframework.data" % "spring-data-jpa" % "1.11.8.RELEASE"` and uncomment `@EnableJpaRepositories` over `PersistenceContext` class
158 |
159 | ## Support
160 |
161 | The play-spring-loader library is *[Community Driven][]*.
162 |
163 | [Community Driven]: https://developer.lightbend.com/docs/lightbend-platform/introduction/getting-help/support-terminology.html#community-driven
164 |
--------------------------------------------------------------------------------
/src/main/scala/com/lightbend/play/spring/DefaultPlayModuleBeanDefinitionReader.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Lightbend
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.lightbend.play.spring
18 |
19 | import java.lang.annotation.Annotation
20 |
21 | import org.springframework.beans.factory.config.{ AutowireCapableBeanFactory, BeanDefinition, ConstructorArgumentValues }
22 | import org.springframework.beans.factory.support.{ AutowireCandidateQualifier, DefaultListableBeanFactory, GenericBeanDefinition }
23 | import org.springframework.core.annotation.AnnotationUtils
24 | import play.api.inject._
25 |
26 | import scala.collection.JavaConverters._
27 |
28 | class DefaultPlayModuleBeanDefinitionReader extends PlayModuleBeanDefinitionReader {
29 |
30 | def bind(beanFactory: DefaultListableBeanFactory, binding: Binding[_]): Unit = {
31 |
32 | // Firstly, if it's an unqualified key being bound to an unqualified alias, then there is no need to
33 | // register anything, Spring by type lookups match all types of the registered bean, there is no need
34 | // to register aliases for other types.
35 | val isSimpleTypeAlias = binding.key.qualifier.isEmpty &&
36 | binding.target.collect {
37 | case b @ BindingKeyTarget(key) if key.qualifier.isEmpty => b
38 | }.nonEmpty
39 |
40 | if (!isSimpleTypeAlias) {
41 |
42 | val beanDef = new GenericBeanDefinition()
43 |
44 | val beanName = binding.key.toString()
45 |
46 | // Add qualifier if it exists
47 | binding.key.qualifier match {
48 | case Some(QualifierClass(clazz)) =>
49 | beanDef.addQualifier(new AutowireCandidateQualifier(clazz))
50 | case Some(QualifierInstance(instance)) =>
51 | beanDef.addQualifier(qualifierFromInstance(instance))
52 | case None =>
53 | // No qualifier, so that means this is the primary binding for that type.
54 | // Setting primary means that if there are both qualified beans and this bean for the same type,
55 | // when an unqualified lookup is done, this one will be selected.
56 | beanDef.setPrimary(true)
57 | }
58 |
59 | // Start with a scope of prototype, if it's singleton, we'll explicitly set that later
60 | beanDef.setScope(BeanDefinition.SCOPE_PROTOTYPE)
61 | // Choose autowire constructor
62 | beanDef.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR)
63 |
64 | binding.target match {
65 | case None =>
66 | beanDef.setBeanClass(binding.key.clazz)
67 | SpringBuilder.maybeSetScope(beanDef, binding.key.clazz)
68 |
69 | case Some(ConstructionTarget(clazz)) =>
70 | // Bound to an implementation, set the impl class as the bean class.
71 | // In this case, the key class is ignored, since Spring does not key beans by type, but a bean is eligible
72 | // for autowiring for all supertypes/interafaces.
73 |
74 | if (clazz.isInterface) {
75 | beanDef.setBeanClass(classOf[BindingKeyFactoryBean[_]])
76 | val args = new ConstructorArgumentValues()
77 | args.addIndexedArgumentValue(0, clazz)
78 | args.addIndexedArgumentValue(1, binding.key.clazz)
79 | args.addIndexedArgumentValue(2, beanFactory)
80 | beanDef.setConstructorArgumentValues(args)
81 | } else {
82 | beanDef.setBeanClass(clazz.asInstanceOf[Class[_]])
83 | SpringBuilder.maybeSetScope(beanDef, clazz.asInstanceOf[Class[_]])
84 | }
85 |
86 | beanDef.setPrimary(false)
87 |
88 | case Some(ProviderConstructionTarget(providerClass)) =>
89 |
90 | val providerBeanName = providerClass.toString
91 |
92 | if (!beanFactory.containsBeanDefinition(providerBeanName)) {
93 |
94 | // The provider itself becomes a bean that gets autowired
95 | val providerBeanDef = new GenericBeanDefinition()
96 | providerBeanDef.setBeanClass(providerClass)
97 | providerClass.getAnnotations.filter(_.annotationType().getName == "javax.inject.Named").foreach {
98 | a: Annotation => beanDef.addQualifier(qualifierFromInstance(a))
99 | }
100 | providerBeanDef.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR)
101 | providerBeanDef.setScope(BeanDefinition.SCOPE_SINGLETON)
102 | providerBeanDef.setAutowireCandidate(false)
103 | beanFactory.registerBeanDefinition(providerBeanName, providerBeanDef)
104 | }
105 |
106 | // And then the provider bean gets used as the factory bean, calling its get method, for the actual bean
107 | beanDef.setFactoryBeanName(providerBeanName)
108 | beanDef.setFactoryMethodName("get")
109 | beanDef.setPrimary(false)
110 |
111 | case Some(ProviderTarget(provider)) =>
112 |
113 | // We have an actual instance of that provider, we create a factory bean to wrap and invoke that provider instance
114 | beanDef.setBeanClass(classOf[ProviderFactoryBean[_]])
115 | val args = new ConstructorArgumentValues()
116 | args.addIndexedArgumentValue(0, provider)
117 | args.addIndexedArgumentValue(1, binding.key.clazz)
118 | args.addIndexedArgumentValue(2, beanFactory)
119 | beanDef.setConstructorArgumentValues(args)
120 |
121 | case Some(BindingKeyTarget(key)) =>
122 |
123 | // It's an alias, create a factory bean that will look up the alias
124 | beanDef.setBeanClass(classOf[BindingKeyFactoryBean[_]])
125 | val args = new ConstructorArgumentValues()
126 | args.addIndexedArgumentValue(0, key)
127 | args.addIndexedArgumentValue(1, binding.key.clazz)
128 | args.addIndexedArgumentValue(2, beanFactory)
129 | beanDef.setConstructorArgumentValues(args)
130 | }
131 |
132 | binding.scope match {
133 | case None =>
134 | // Do nothing, we've already defaulted or detected the scope
135 | case Some(scope) =>
136 | SpringBuilder.setScope(beanDef, scope)
137 | }
138 |
139 | beanFactory.registerBeanDefinition(beanName, beanDef)
140 | }
141 | }
142 |
143 | /**
144 | * Turns an instance of an annotation into a spring qualifier descriptor.
145 | */
146 | private def qualifierFromInstance(instance: Annotation) = {
147 | val annotationType = instance.annotationType()
148 | val qualifier = new AutowireCandidateQualifier(annotationType)
149 | AnnotationUtils.getAnnotationAttributes(instance).asScala.foreach {
150 | case (attribute, value) => qualifier.setAttribute(attribute, value)
151 | }
152 |
153 | qualifier
154 | }
155 |
156 | }
157 |
158 | object DefaultPlayModuleBeanDefinitionReader {
159 |
160 | def apply() = new DefaultPlayModuleBeanDefinitionReader()
161 |
162 | }
163 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/src/main/scala/com/lightbend/play/spring/SpringBuilder.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Lightbend
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.lightbend.play.spring
18 |
19 | import java.io.File
20 | import java.lang.annotation.Annotation
21 | import javax.inject.Provider
22 |
23 | import com.typesafe.config.Config
24 | import org.springframework.beans.TypeConverter
25 | import org.springframework.beans.factory.annotation.{ AutowiredAnnotationBeanPostProcessor, QualifierAnnotationAutowireCandidateResolver }
26 | import org.springframework.beans.factory.config.{ AutowireCapableBeanFactory, BeanDefinition, BeanDefinitionHolder }
27 | import org.springframework.beans.factory.support._
28 | import org.springframework.beans.factory.{ FactoryBean, NoSuchBeanDefinitionException, NoUniqueBeanDefinitionException }
29 | import org.springframework.context.annotation.AnnotationConfigApplicationContext
30 | import play.api._
31 | import play.api.inject._
32 |
33 | import scala.collection.JavaConverters._
34 | import scala.reflect.ClassTag
35 |
36 | /**
37 | * A builder for creating Spring-backed Play Injectors.
38 | */
39 | abstract class SpringBuilder[Self] protected (
40 | environment: Environment,
41 | configuration: Configuration,
42 | modules: Seq[Module],
43 | overrides: Seq[Module],
44 | disabled: Seq[Class[_]],
45 | beanReader: PlayModuleBeanDefinitionReader) {
46 |
47 | /**
48 | * Set the environment.
49 | */
50 | final def in(env: Environment): Self =
51 | copyBuilder(environment = env)
52 |
53 | /**
54 | * Set the environment path.
55 | */
56 | final def in(path: File): Self =
57 | copyBuilder(environment = environment.copy(rootPath = path))
58 |
59 | /**
60 | * Set the environment mode.
61 | */
62 | final def in(mode: Mode): Self =
63 | copyBuilder(environment = environment.copy(mode = mode))
64 |
65 | /**
66 | * Set the environment class loader.
67 | */
68 | final def in(classLoader: ClassLoader): Self =
69 | copyBuilder(environment = environment.copy(classLoader = classLoader))
70 |
71 | /**
72 | * Add additional configuration.
73 | */
74 | final def configure(conf: Config): Self =
75 | configure(Configuration(conf))
76 |
77 | /**
78 | * Add additional configuration.
79 | */
80 | final def configure(conf: Configuration): Self =
81 | copyBuilder(configuration = configuration ++ conf)
82 |
83 | /**
84 | * Add additional configuration.
85 | */
86 | final def configure(conf: Map[String, Any]): Self =
87 | configure(Configuration.from(conf))
88 |
89 | /**
90 | * Add additional configuration.
91 | */
92 | final def configure(conf: (String, Any)*): Self =
93 | configure(conf.toMap)
94 |
95 | /**
96 | * Add Play modules or Play bindings.
97 | */
98 | @annotation.varargs
99 | final def bindings(bindModules: Module*): Self =
100 | copyBuilder(modules = modules ++ bindModules)
101 |
102 | /**
103 | * Disable modules by class.
104 | */
105 | @annotation.varargs
106 | final def disable(moduleClasses: Class[_]*): Self =
107 | copyBuilder(disabled = disabled ++ moduleClasses)
108 |
109 | /**
110 | * Override bindings using Spring modules, Play modules, or Play bindings.
111 | */
112 | @annotation.varargs
113 | final def overrides(overrideModules: Module*): Self =
114 | copyBuilder(overrides = overrides ++ overrideModules)
115 |
116 | /**
117 | * Override beanReader
118 | */
119 | final def withBeanReader(beanReader: PlayModuleBeanDefinitionReader): Self =
120 | copyBuilder(beanReader = beanReader)
121 |
122 | def createModules(): Seq[Module] = {
123 |
124 | val injectorModule = new Module {
125 | def bindings(environment: Environment, configuration: Configuration) = Seq(
126 | bind[play.inject.Injector].to[play.inject.DelegateInjector])
127 | }
128 | val enabledModules: Seq[Module] = filterOut(disabled, modules)
129 | val bindingModules: Seq[Module] = enabledModules :+ injectorModule
130 | val springableOverrides: Seq[Module] = overrides.map(SpringableModule.springable)
131 | bindingModules ++ springableOverrides
132 | }
133 |
134 | private def filterOut[A](classes: Seq[Class[_]], instances: Seq[A]): Seq[A] =
135 | instances.filterNot(o => classes.exists(_.isAssignableFrom(o.getClass)))
136 |
137 | /**
138 | * Disable module by class.
139 | */
140 | final def disable[T](implicit tag: ClassTag[T]): Self = disable(tag.runtimeClass)
141 |
142 | def prepareConfig(): Self
143 |
144 | def injector(): Injector = {
145 | springInjector()
146 | }
147 |
148 | def springInjector(): Injector = {
149 | val ctx = new AnnotationConfigApplicationContext()
150 |
151 | val beanFactory = ctx.getDefaultListableBeanFactory
152 |
153 | beanFactory.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver())
154 |
155 | val injector = new SpringInjector(beanFactory)
156 | // Register the Spring injector as a singleton first
157 | beanFactory.registerSingleton("play-injector", injector)
158 |
159 | //build modules
160 | val modulesToRegister = createModules()
161 |
162 | val disabledBindings = configuration.get[Seq[String]]("play.spring.bindings.disabled")
163 | val disabledBindingClasses: Seq[Class[_]] = disabledBindings.map(className => loadClass(className))
164 |
165 | //register modules
166 | modulesToRegister.foreach {
167 | case playModule: Module =>
168 | playModule.bindings(environment, configuration)
169 | .filter(b => !disabledBindingClasses.contains(b.key.clazz))
170 | .foreach(b => beanReader.bind(beanFactory, b))
171 | case unknown => throw new PlayException(
172 | "Unknown module type",
173 | s"Module [$unknown] is not a Play module")
174 | }
175 |
176 | val springConfig = configuration.get[Seq[String]]("play.spring.configs")
177 | val confClasses: Seq[Class[_]] = springConfig.map(className => loadClass(className))
178 | if (confClasses.nonEmpty) {
179 | ctx.register(confClasses: _*)
180 | }
181 |
182 | ctx.refresh()
183 | ctx.start()
184 |
185 | injector
186 | }
187 |
188 | def loadClass(className: String): Class[_] = {
189 | try {
190 | environment.classLoader.loadClass(className)
191 | } catch {
192 | case e: ClassNotFoundException => throw e
193 | case e: VirtualMachineError => throw e
194 | case e: ThreadDeath => throw e
195 | case e: Throwable =>
196 | throw new PlayException(s"Cannot load $className", s"[$className] was not loaded.", e)
197 | }
198 | }
199 |
200 | /**
201 | * Internal copy method with defaults.
202 | */
203 | private def copyBuilder(
204 | environment: Environment = environment,
205 | configuration: Configuration = configuration,
206 | modules: Seq[Module] = modules,
207 | overrides: Seq[Module] = overrides,
208 | disabled: Seq[Class[_]] = disabled,
209 | beanReader: PlayModuleBeanDefinitionReader = beanReader): Self =
210 | newBuilder(environment, configuration, modules, overrides, disabled, beanReader)
211 |
212 | /**
213 | * Create a new Self for this immutable builder.
214 | * Provided by builder implementations.
215 | */
216 | protected def newBuilder(
217 | environment: Environment,
218 | configuration: Configuration,
219 | modules: Seq[Module],
220 | overrides: Seq[Module],
221 | disabled: Seq[Class[_]],
222 | beanReader: PlayModuleBeanDefinitionReader): Self
223 |
224 | }
225 |
226 | private object SpringBuilder {
227 | /**
228 | * Set the scope on the given bean definition if a scope annotation is declared on the class.
229 | */
230 | def maybeSetScope(bd: GenericBeanDefinition, clazz: Class[_]) {
231 | clazz.getAnnotations.foreach { annotation =>
232 | if (annotation.annotationType().getAnnotations.exists(_.annotationType() == classOf[javax.inject.Scope])) {
233 | setScope(bd, annotation.annotationType())
234 | }
235 | }
236 | }
237 |
238 | /**
239 | * Set the given scope annotation scope on the given bean definition.
240 | */
241 | def setScope(bd: GenericBeanDefinition, clazz: Class[_ <: Annotation]) = {
242 | clazz match {
243 | case singleton if singleton == classOf[javax.inject.Singleton] =>
244 | bd.setScope(BeanDefinition.SCOPE_SINGLETON)
245 | case other =>
246 | // todo: use Jsr330ScopeMetaDataResolver to resolve and set scope
247 | }
248 | }
249 | }
250 |
251 | /**
252 | * A factory bean that wraps a binding key alias.
253 | */
254 | class BindingKeyFactoryBean[T](key: BindingKey[T], objectType: Class[_], factory: DefaultListableBeanFactory) extends FactoryBean[T] {
255 | /**
256 | * The bean name, if it can be determined.
257 | *
258 | * Will either return a new bean name, or if the by type lookup should be done on request (in the case of an
259 | * unqualified lookup because it's cheaper to delegate that to Spring) then do it on request. Will throw an
260 | * exception if a key for which no matching bean can be found is found.
261 | */
262 | lazy val beanName: Option[String] = {
263 | key.qualifier match {
264 | case None =>
265 | None
266 | case Some(QualifierClass(qualifier)) =>
267 | val candidates = factory.getBeanNamesForType(key.clazz)
268 | val matches = candidates.toList
269 | .map(name => new BeanDefinitionHolder(factory.getBeanDefinition(name), name))
270 | .filter { bdh =>
271 | bdh.getBeanDefinition match {
272 | case abd: AbstractBeanDefinition =>
273 | abd.hasQualifier(qualifier.getName)
274 | case _ => false
275 | }
276 | }.map(_.getBeanName)
277 | getNameFromMatches(matches)
278 | case Some(QualifierInstance(qualifier)) =>
279 | val candidates = factory.getBeanNamesForType(key.clazz)
280 | val matches = candidates.toList
281 | .map(name => new BeanDefinitionHolder(factory.getBeanDefinition(name), name))
282 | .filter(bdh => QualifierChecker.checkQualifier(bdh, qualifier, factory.getTypeConverter))
283 | .map(_.getBeanName)
284 | getNameFromMatches(matches)
285 | }
286 | }
287 |
288 | private def getNameFromMatches(candidates: Seq[String]): Option[String] = {
289 | candidates match {
290 | case Nil => throw new NoSuchBeanDefinitionException(key.clazz, "Binding alias for type " + objectType + " to " + key,
291 | "No bean found for binding alias")
292 | case single :: Nil => Some(single)
293 | case multiple => throw new NoUniqueBeanDefinitionException(key.clazz, multiple.asJava)
294 | }
295 |
296 | }
297 |
298 | def getObject = {
299 | beanName.fold(factory.getBean(key.clazz))(name => factory.getBean(name).asInstanceOf[T])
300 | }
301 |
302 | def getObjectType = objectType
303 |
304 | def isSingleton = false
305 | }
306 |
307 | /**
308 | * A factory bean that wraps a provider.
309 | */
310 | class ProviderFactoryBean[T](provider: Provider[T], objectType: Class[_], factory: AutowireCapableBeanFactory)
311 | extends FactoryBean[T] {
312 |
313 | lazy val injectedProvider = {
314 | // Autowire the providers properties - Play needs this in a few places.
315 | val bpp = new AutowiredAnnotationBeanPostProcessor()
316 | bpp.setBeanFactory(factory)
317 | bpp.processInjection(provider)
318 | provider
319 | }
320 |
321 | def getObject = injectedProvider.get()
322 |
323 | def getObjectType = objectType
324 |
325 | def isSingleton = false
326 | }
327 |
328 | /**
329 | * Hack to expose the checkQualifier method as public.
330 | */
331 | object QualifierChecker extends QualifierAnnotationAutowireCandidateResolver {
332 |
333 | /**
334 | * Override to expose as public
335 | */
336 | override def checkQualifier(bdHolder: BeanDefinitionHolder, annotation: Annotation, typeConverter: TypeConverter) = {
337 | bdHolder.getBeanDefinition match {
338 | case root: RootBeanDefinition => super.checkQualifier(bdHolder, annotation, typeConverter)
339 | case nonRoot =>
340 | val bdh = new BeanDefinitionHolder(RootBeanDefinitionCreator.create(nonRoot), bdHolder.getBeanName)
341 | super.checkQualifier(bdh, annotation, typeConverter)
342 | }
343 | }
344 | }
345 |
--------------------------------------------------------------------------------